Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

feat: add Jev review gates to data analyst

Tiioluwanic0fd457f738d
diff --git a/ai_agents/nl_data_analyst_agent/.env.example b/ai_agents/nl_data_analyst_agent/.env.example
index 19cb936..e7a29b6 100644
--- a/ai_agents/nl_data_analyst_agent/.env.example
+++ b/ai_agents/nl_data_analyst_agent/.env.example
@@ -1,5 +1,10 @@
AI_GATEWAY_API_KEY=
EVE_URL=http://127.0.0.1:3000
+JEV_MODEL=typesafe-ai/jev
+JEV_MIN_CONFIDENCE=0.70
+JEV_TIMEOUT_SECONDS=10
+# Optional: override only when using a compatible Jev evaluation endpoint.
+JEV_URL=https://ai-gateway.vercel.sh/v1/evaluate
DATABASE_PATH=
GRADIO_SERVER_NAME=127.0.0.1
GRADIO_SERVER_PORT=7860
diff --git a/ai_agents/nl_data_analyst_agent/README.md b/ai_agents/nl_data_analyst_agent/README.md
index 66005c3..4acc244 100644
--- a/ai_agents/nl_data_analyst_agent/README.md
+++ b/ai_agents/nl_data_analyst_agent/README.md
@@ -1,6 +1,6 @@
# Natural Language Data Analyst Agent
-An analyst built with [Vercel Eve](https://github.com/vercel/eve) that lets you ask questions about a SQLite database in plain English. You describe the analysis you need instead of writing SQL yourself. The agent writes read-only SQL, shows the results, and asks for approval before broad queries run.
+An analyst built with [Vercel Eve](https://github.com/vercel/eve) that lets you ask questions about a SQLite database in plain English. You describe the analysis you need instead of writing SQL yourself. The agent writes read-only SQL, shows the results, and asks for approval before broad queries run. [Jev](https://vercel.com/ai-gateway/models/jev) reviews question clarity, SQL relevance, and answer grounding without replacing Qwen as the SQL or explanation writer.
![Natural Language Data Analyst Agent demo](assets/demo.gif)
@@ -10,7 +10,15 @@ Connect a SQLite file in Gradio by uploading it, entering its local path, or loa
The included sales example contains fictional customers, products, and orders from 2025. In this dataset, revenue is `quantity * unit_price` for completed orders. When you connect your own database, the agent uses its schema without assuming the same revenue definition.
-Eve's SQL tool pauses for approval when a query has no `WHERE` clause. You can review the proposed SQL in Gradio, then approve or reject it before the query runs.
+Eve's SQL tool pauses for approval when a query has no `WHERE` clause. You can review the proposed SQL in Gradio, then approve or reject it before the query runs. Gradio associates proposed SQL, results, and approvals by Eve call ID, so an approval prompt always shows its own SQL and never displays rows returned by a different call. If another call completed in the same turn, those results are hidden during review and can be restored after rejection with an explicit label.
+
+Jev makes narrow, structured judgments with confidence values at three interception points:
+
+1. Before Gradio sends a question to Eve, Jev sees the selected schema and known demo metric definition. A confident missing-definition judgment asks the user to clarify; clear questions proceed.
+2. After Qwen proposes SQL, `run_sql` sends Jev the authoritative question bound from Eve's `message.received` event, plus the schema and validated SQL, before database execution. Qwen cannot supply or rewrite the reviewed question. A confident mismatch with a specific issue returns a structured review to Eve without running the query, giving Eve one revision attempt.
+3. After SQLite returns rows and Eve completes its explanation, Gradio sends Jev the question, executed SQL, rows, and explanation before displaying it. A confident grounding mismatch is presented as an **unverified draft awaiting user review**, ahead of Eve's text, with an exact follow-up prompt for revision. The SQL and rows remain visible for comparison.
+
+The default confidence threshold is `0.70`. Low-confidence judgments, inconsistent verdict/issue pairs, and Jev API failures fail open for availability and are displayed as reviewer notes. A mismatch without a specific issue is treated as inconclusive rather than blocking. A non-mismatch verdict ignores a contradictory issue label. These outcomes never relax SQL validation, approve a query, or bypass human approval. Jev is a reviewer only; Qwen continues to generate SQL and prose.
## Tech Stack
@@ -20,6 +28,7 @@ Eve's SQL tool pauses for approval when a query has no `WHERE` clause. You can r
| Agent runtime and approval | Vercel Eve `0.63.0` |
| Model gateway | Vercel AI Gateway |
| Exact model | `alibaba/qwen3.8-omni-flash` |
+| Structured reviewer | `typesafe-ai/jev` |
| Agent tools | TypeScript, Zod, Node SQLite |
| Interface | Gradio |
| Data | SQLite |
@@ -54,7 +63,18 @@ pnpm install
uv sync
```
-Edit `.env` and set `AI_GATEWAY_API_KEY` to your own key. Never commit this file. `EVE_URL` defaults to `http://127.0.0.1:3000`. You can optionally set `DATABASE_PATH` to prefill the path control in Gradio. Leave `GRADIO_SERVER_NAME=127.0.0.1` for local use.
+Edit `.env` and set `AI_GATEWAY_API_KEY` to your own key. The same Vercel AI Gateway key is used by Eve/Qwen and all three Jev reviews. Never commit this file. `EVE_URL` defaults to `http://127.0.0.1:3000`. You can optionally set `DATABASE_PATH` to prefill the path control in Gradio. Leave `GRADIO_SERVER_NAME=127.0.0.1` for local use.
+
+Reviewer settings are optional:
+
+```dotenv
+JEV_MODEL=typesafe-ai/jev
+JEV_MIN_CONFIDENCE=0.70
+JEV_TIMEOUT_SECONDS=10
+JEV_URL=https://ai-gateway.vercel.sh/v1/evaluate
+```
+
+`JEV_URL` is used by the Python/Gradio checks. Those checks read reviewer settings when each request runs, after `.env` has loaded. Eve's TypeScript `evaluate` helper resolves `JEV_MODEL` through its configured AI Gateway connection. Raise the confidence threshold after calibrating the three judgments on representative questions. If credentials or Jev are unavailable, the app continues and adds a visible “review unavailable” note.
The demo button seeds the example database automatically. To seed it in advance:
@@ -88,7 +108,9 @@ The last question demonstrates the approval controls. You can also say “Hi”
## Safety and Scope
-The SQL tool accepts one `SELECT`, opens SQLite read-only, and enables query-only mode. Queries returning more than 200 rows are rejected with a prompt to add aggregation or `LIMIT`. Eve requests approval before executing queries without a `WHERE` clause. This rule catches broad queries but does not estimate their cost.
+The SQL tool accepts one `SELECT`, opens SQLite read-only, and enables query-only mode. Queries returning more than 200 rows are rejected with a prompt to add aggregation or `LIMIT`. Eve requests approval before executing queries without a `WHERE` clause. This rule catches broad queries but does not estimate their cost. These deterministic controls run independently of Jev. A Jev result cannot authorize SQL, change permissions, override rejection, or answer an approval request.
+
+The SQL relevance check is inside `run_sql`, immediately before statement execution. Eve's stream exposes `actions.requested` before execution, but Gradio consuming that event cannot reliably cancel the server-side tool call. Placing the gate in the tool is therefore the smallest sound interception point. An Eve hook captures the exact Gradio message from the durable `message.received` event and stores its database ID, question, and turn ID in per-session state. `run_sql` accepts no question field and refuses an unbound database or turn, so the model cannot substitute the text Jev reviews.
This project runs locally with SQLite files. To deploy it for other users or connect a production database, add authentication, access controls, and stronger query limits. Database paths are stored in the ignored `data/connections.json` file. Keep database files containing sensitive data and `.env` out of Git.
@@ -98,9 +120,12 @@ The commands below are optional checks, not steps required to open the UI:
```powershell
pnpm run build
+pnpm test
uv run --extra dev python -m pytest -q
```
+All automated Jev tests use mocked evaluator responses and require no API key or paid model call. A live end-to-end run still requires an AI Gateway key with access to both configured models.
+
The GIF above shows the working Gradio application.
## Project Structure
@@ -110,12 +135,16 @@ nl_data_analyst_agent/
├── agent/
│ ├── agent.ts # Eve model configuration
│ ├── instructions.md # Analyst behavior
+│ ├── hooks/capture_question.ts # Bind authoritative questions to Eve turns
│ ├── lib/database.ts # SQLite access and SQL checks
+│ ├── lib/jev.ts # Pre-execution SQL relevance review
+│ ├── lib/question_context.ts # Per-session question binding
│ └── tools/ # Eve schema and query tools
├── main.py # Gradio client for Eve sessions
+├── jev_review.py # Question and answer Jev reviews
├── seed_data.py # Fictional demo database
├── tests/ # Offline UI checks
-├── assets/how_it_works.png
+├── assets/demo.gif # Gradio application demo
├── package.json
├── pnpm-lock.yaml
├── pyproject.toml
@@ -124,4 +153,4 @@ nl_data_analyst_agent/
## Resources
-[Eve documentation](https://eve.dev/docs) · [Eve HTTP sessions](https://github.com/vercel/eve/blob/main/docs/channels/eve.mdx) · [Eve human approval](https://github.com/vercel/eve/blob/main/docs/tutorial/guard-the-spend.mdx) · [Vercel AI Gateway](https://vercel.com/docs/ai-gateway) · [Gradio documentation](https://www.gradio.app/docs)
+[Jev through AI SDK and Eve](https://vercel.com/i/jev-integrations) · [Jev on AI Gateway](https://vercel.com/ai-gateway/models/jev) · [Eve evaluation](https://github.com/vercel/eve/blob/main/docs/guides/evaluate.md) · [Eve sessions and stream events](https://github.com/vercel/eve/blob/main/docs/concepts/sessions-runs-and-streaming.md) · [Eve human approval](https://github.com/vercel/eve/blob/main/docs/tutorial/guard-the-spend.mdx) · [Gradio documentation](https://www.gradio.app/docs)
diff --git a/ai_agents/nl_data_analyst_agent/agent/hooks/capture_question.ts b/ai_agents/nl_data_analyst_agent/agent/hooks/capture_question.ts
new file mode 100644
index 0000000..8c167ce
--- /dev/null
+++ b/ai_agents/nl_data_analyst_agent/agent/hooks/capture_question.ts
@@ -0,0 +1,12 @@
+import { defineHook } from "eve/hooks";
+import { currentQuestion, parseAnalystMessage } from "../lib/question_context";
+
+export default defineHook({
+ events: {
+ "message.received"(event) {
+ if (event.data.kind === "execution.background_task") return;
+ const binding = parseAnalystMessage(event.data.message, event.data.turnId);
+ currentQuestion.update(() => binding);
+ },
+ },
+});
diff --git a/ai_agents/nl_data_analyst_agent/agent/instructions.md b/ai_agents/nl_data_analyst_agent/agent/instructions.md
index 68e0955..13c7010 100644
--- a/ai_agents/nl_data_analyst_agent/agent/instructions.md
+++ b/ai_agents/nl_data_analyst_agent/agent/instructions.md
@@ -1,5 +1,5 @@
You are a careful SQLite data analyst. Each user message from the Gradio app contains a database ID and a question. Use only that database ID for tools; never substitute another ID or infer a file path.
-For a data question, call inspect_schema first. Then compose one SQLite SELECT using only columns in that schema and call run_sql. Explain the actual returned rows, show the metric definition and limitations, and never invent values, units, currencies, or causal explanations. For the demo database only, completed-order revenue is quantity * unit_price for orders with status = 'completed'. Other databases have no assumed revenue rule.
+For a data question, call inspect_schema first. Then compose one SQLite SELECT using only columns in that schema and call run_sql. Issue only one run_sql call at a time; wait for its result or approval decision before proposing another SQL query. The runtime binds run_sql to the actual question received for this turn; do not restate or reinterpret the question in tool input. If run_sql returns `execution: "blocked"`, use its Jev review to revise the SQL and try once more; do not claim that the blocked SQL ran. Explain the actual returned rows, show the metric definition and limitations, and never invent values, units, currencies, or causal explanations. For the demo database only, completed-order revenue is quantity * unit_price for orders with status = 'completed'. Other databases have no assumed revenue rule.
Use LIMIT for detail queries. Aggregates are allowed without LIMIT. If the query requires approval, wait for the user. If approval is denied, explain that no query was run and do not retry or substitute another query. Do not call tools for a greeting or a question unrelated to the selected database. You cannot access external data or execute Python.
diff --git a/ai_agents/nl_data_analyst_agent/agent/lib/database.ts b/ai_agents/nl_data_analyst_agent/agent/lib/database.ts
index 25f8e2e..549970b 100644
--- a/ai_agents/nl_data_analyst_agent/agent/lib/database.ts
+++ b/ai_agents/nl_data_analyst_agent/agent/lib/database.ts
@@ -16,6 +16,15 @@ export function openDatabase(databaseId: string): DatabaseSync {
return db;
}
+export function inspectDatabaseSchema(db: DatabaseSync) {
+ const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all() as { name: string }[];
+ return tables.map(({ name }) => {
+ const quoted = `"${name.replaceAll('"', '""')}"`;
+ const columns = db.prepare(`PRAGMA table_info(${quoted})`).all() as { name: string; type: string }[];
+ return { table: name, columns: columns.map(({ name, type }) => ({ name, type })) };
+ });
+}
+
export function validateSql(sql: string): string {
const cleaned = sql.trim().replace(/;\s*$/, "");
if (!/^select\b/i.test(cleaned) || cleaned.includes(";")) {
diff --git a/ai_agents/nl_data_analyst_agent/agent/lib/jev.ts b/ai_agents/nl_data_analyst_agent/agent/lib/jev.ts
new file mode 100644
index 0000000..6af78ba
--- /dev/null
+++ b/ai_agents/nl_data_analyst_agent/agent/lib/jev.ts
@@ -0,0 +1,84 @@
+import { evaluate } from "eve/ai";
+
+export const JEV_MIN_CONFIDENCE = 0.70;
+
+export interface SqlReview {
+ check: "SQL relevance";
+ verdict: "relevant" | "mismatch" | "unavailable";
+ confidence: number | null;
+ issue: string;
+ actionable: boolean;
+ status: "ok" | "low_confidence" | "inconsistent" | "error";
+}
+
+type Evaluate = typeof evaluate;
+
+const issueText: Record<string, string> = {
+ none: "The SQL addresses the question.",
+ wrong_metric: "The SQL calculates a different metric from the one requested.",
+ wrong_filter: "The SQL filters the wrong records or time range.",
+ wrong_grouping: "The SQL groups or compares the data differently from the question.",
+ wrong_entities: "The SQL uses the wrong tables, entities, or join relationship.",
+};
+
+export async function reviewSqlRelevance(
+ state: { question: string; sql: string; databaseSchema: unknown },
+ evaluateFn: Evaluate = evaluate,
+): Promise<SqlReview> {
+ try {
+ const result = await evaluateFn({
+ model: process.env.JEV_MODEL ?? "typesafe-ai/jev",
+ state,
+ maxRetries: 1,
+ abortSignal: AbortSignal.timeout(Number(process.env.JEV_TIMEOUT_SECONDS ?? "10") * 1000),
+ questions: {
+ verdict: {
+ type: "choice",
+ instructions: "Judge whether the proposed SQLite SELECT directly addresses the user's data question using the supplied schema.",
+ criteria: {
+ relevant: "The query's metric, filters, grouping, entities, and requested detail match the question.",
+ mismatch: "A material part of the query does not match the question.",
+ },
+ },
+ issue: {
+ type: "choice",
+ instructions: "Select the single most important mismatch, or none.",
+ criteria: {
+ none: issueText.none,
+ wrong_metric: issueText.wrong_metric,
+ wrong_filter: issueText.wrong_filter,
+ wrong_grouping: issueText.wrong_grouping,
+ wrong_entities: issueText.wrong_entities,
+ },
+ },
+ },
+ });
+ const verdict = result.answers.verdict.choice as "relevant" | "mismatch";
+ const confidence = result.answers.verdict.confidence;
+ const issueKey = result.answers.issue.choice;
+ const threshold = Number(process.env.JEV_MIN_CONFIDENCE ?? JEV_MIN_CONFIDENCE);
+ const inconsistent = (verdict === "mismatch") === (issueKey === "none");
+ const issue = inconsistent
+ ? verdict === "mismatch"
+ ? "Jev reported a mismatch without identifying a specific issue; the query proceeded as inconclusive."
+ : issueText.none
+ : issueText[issueKey] ?? "Review the proposed SQL against the question.";
+ return {
+ check: "SQL relevance",
+ verdict,
+ confidence,
+ issue,
+ actionable: verdict === "mismatch" && confidence >= threshold && !inconsistent,
+ status: inconsistent ? "inconsistent" : confidence >= threshold ? "ok" : "low_confidence",
+ };
+ } catch (error) {
+ return {
+ check: "SQL relevance",
+ verdict: "unavailable",
+ confidence: null,
+ issue: `Review unavailable: ${error instanceof Error ? error.message : String(error)}`,
+ actionable: false,
+ status: "error",
+ };
+ }
+}
diff --git a/ai_agents/nl_data_analyst_agent/agent/lib/question_context.ts b/ai_agents/nl_data_analyst_agent/agent/lib/question_context.ts
new file mode 100644
index 0000000..0512d30
--- /dev/null
+++ b/ai_agents/nl_data_analyst_agent/agent/lib/question_context.ts
@@ -0,0 +1,32 @@
+import { defineState } from "eve/context";
+
+export interface QuestionBinding {
+ databaseId: string;
+ question: string;
+ turnId: string;
+}
+
+export const currentQuestion = defineState<QuestionBinding | null>(
+ "nl-data-analyst.current-question",
+ () => null,
+);
+
+export function parseAnalystMessage(message: string, turnId: string): QuestionBinding | null {
+ const match = /^Database ID: ([^\r\n]+)\r?\nQuestion: ([\s\S]+)$/.exec(message);
+ if (!match) return null;
+ const databaseId = match[1].trim();
+ const question = match[2].trim();
+ if (!databaseId || !question) return null;
+ return { databaseId, question, turnId };
+}
+
+export function boundQuestionFor(
+ binding: QuestionBinding | null,
+ databaseId: string,
+ turnId: string,
+): string {
+ if (!binding || binding.databaseId !== databaseId || binding.turnId !== turnId) {
+ throw new Error("The SQL call is not bound to the current user question. Start a new analysis turn.");
+ }
+ return binding.question;
+}
diff --git a/ai_agents/nl_data_analyst_agent/agent/tools/inspect_schema.ts b/ai_agents/nl_data_analyst_agent/agent/tools/inspect_schema.ts
index 0c7e7fb..dbce215 100644
--- a/ai_agents/nl_data_analyst_agent/agent/tools/inspect_schema.ts
+++ b/ai_agents/nl_data_analyst_agent/agent/tools/inspect_schema.ts
@@ -1,6 +1,6 @@
import { defineTool } from "eve/tools";
import { z } from "zod";
-import { openDatabase } from "../lib/database";
+import { inspectDatabaseSchema, openDatabase } from "../lib/database";
export default defineTool({
description: "Read table names and columns of the currently selected SQLite database.",
@@ -8,12 +8,7 @@ export default defineTool({
execute({ databaseId }) {
const db = openDatabase(databaseId);
try {
- const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all() as { name: string }[];
- return tables.map(({ name }) => {
- const quoted = `"${name.replaceAll('"', '""')}"`;
- const columns = db.prepare(`PRAGMA table_info(${quoted})`).all() as { name: string; type: string }[];
- return { table: name, columns: columns.map(({ name, type }) => ({ name, type })) };
- });
+ return inspectDatabaseSchema(db);
} finally {
db.close();
}
diff --git a/ai_agents/nl_data_analyst_agent/agent/tools/run_sql.ts b/ai_agents/nl_data_analyst_agent/agent/tools/run_sql.ts
index e73cee0..271867c 100644
--- a/ai_agents/nl_data_analyst_agent/agent/tools/run_sql.ts
+++ b/ai_agents/nl_data_analyst_agent/agent/tools/run_sql.ts
@@ -1,19 +1,26 @@
import { defineTool } from "eve/tools";
import { z } from "zod";
-import { needsApproval, openDatabase, validateSql } from "../lib/database";
+import { inspectDatabaseSchema, needsApproval, openDatabase, validateSql } from "../lib/database";
+import { reviewSqlRelevance } from "../lib/jev";
+import { boundQuestionFor, currentQuestion } from "../lib/question_context";
export default defineTool({
description: "Execute one read-only SQLite SELECT on the selected database. Broad queries without a WHERE filter require the engineer's approval before execution.",
inputSchema: z.object({ databaseId: z.string(), sql: z.string().min(1).max(10000) }),
approval: ({ toolInput }) => needsApproval(toolInput?.sql ?? "") ? "user-approval" : "not-applicable",
- execute({ databaseId, sql }) {
+ async execute({ databaseId, sql }, ctx) {
const safe = validateSql(sql);
+ const question = boundQuestionFor(currentQuestion.get(), databaseId, ctx.session.turn.id);
const db = openDatabase(databaseId);
try {
+ const review = await reviewSqlRelevance({ question, sql: safe, databaseSchema: inspectDatabaseSchema(db) });
+ if (review.actionable) {
+ return { sql: safe, columns: [], rows: [], review, execution: "blocked" as const };
+ }
const statement = db.prepare(safe);
const rows = db.prepare(`SELECT * FROM (${safe}) LIMIT 201`).all() as Record<string, unknown>[];
if (rows.length > 200) throw new Error("Query returned more than 200 rows. Add aggregation or LIMIT.");
- return { sql: safe, columns: rows.length ? Object.keys(rows[0]) : statement.columns().map(column => column.name), rows };
+ return { sql: safe, columns: rows.length ? Object.keys(rows[0]) : statement.columns().map(column => column.name), rows, review, execution: "completed" as const };
} finally {
db.close();
}
diff --git a/ai_agents/nl_data_analyst_agent/jev_review.py b/ai_agents/nl_data_analyst_agent/jev_review.py
new file mode 100644
index 0000000..def1411
--- /dev/null
+++ b/ai_agents/nl_data_analyst_agent/jev_review.py
@@ -0,0 +1,132 @@
+"""Small, typed Jev review client for the Gradio-side checks."""
+
+from __future__ import annotations
+
+import os
+from dataclasses import dataclass
+from typing import Any
+
+import httpx
+
+DEFAULT_JEV_URL = "https://ai-gateway.vercel.sh/v1/evaluate"
+DEFAULT_JEV_MODEL = "typesafe-ai/jev"
+DEFAULT_JEV_MIN_CONFIDENCE = 0.70
+
+
+def jev_url() -> str:
+ return os.getenv("JEV_URL", DEFAULT_JEV_URL)
+
+
+def jev_model() -> str:
+ return os.getenv("JEV_MODEL", DEFAULT_JEV_MODEL)
+
+
+def jev_min_confidence() -> float:
+ return float(os.getenv("JEV_MIN_CONFIDENCE", str(DEFAULT_JEV_MIN_CONFIDENCE)))
+
+
+@dataclass(frozen=True)
+class Review:
+ check: str
+ verdict: str
+ confidence: float | None
+ issue: str
+ actionable: bool
+ status: str = "ok"
+
+ def message(self) -> str:
+ confidence = "unknown" if self.confidence is None else f"{self.confidence:.0%}"
+ return f"Jev {self.check}: {self.verdict} ({confidence} confidence). {self.issue}"
+
+
+def _post_jev(payload: dict[str, Any]) -> dict[str, Any]:
+ key = os.getenv("AI_GATEWAY_API_KEY", "").strip()
+ if not key:
+ raise RuntimeError("AI_GATEWAY_API_KEY is not configured")
+ response = httpx.post(
+ jev_url(),
+ headers={"Authorization": f"Bearer {key}"},
+ json=payload,
+ timeout=float(os.getenv("JEV_TIMEOUT_SECONDS", "10")),
+ )
+ response.raise_for_status()
+ return response.json()
+
+
+def _choice_review(
+ *,
+ check: str,
+ state: dict[str, Any],
+ verdicts: dict[str, str],
+ issues: dict[str, str],
+ actionable_verdict: str,
+) -> Review:
+ questions = {
+ "verdict": {
+ "type": "choice",
+ "instructions": f"Make the focused {check} judgment described by the criteria.",
+ "criteria": verdicts,
+ },
+ "issue": {
+ "type": "choice",
+ "instructions": "Select the single most important issue, or none.",
+ "criteria": issues,
+ },
+ }
+ try:
+ body = _post_jev({"model": jev_model(), "state": state, "questions": questions})
+ answers = body["answers"]
+ verdict_answer = answers["verdict"]
+ verdict = str(verdict_answer["choice"])
+ confidence = float(verdict_answer["confidence"])
+ issue_key = str(answers["issue"]["choice"])
+ issue = issues.get(issue_key, issue_key.replace("_", " "))
+ threshold = jev_min_confidence()
+ inconsistent = (verdict == actionable_verdict) == (issue_key == "none")
+ if inconsistent and verdict == actionable_verdict:
+ issue = "Jev requested review without identifying a specific issue; treated as inconclusive."
+ elif inconsistent:
+ issue = issues["none"]
+ actionable = verdict == actionable_verdict and confidence >= threshold and not inconsistent
+ status = "inconsistent" if inconsistent else ("ok" if confidence >= threshold else "low_confidence")
+ return Review(check, verdict, confidence, issue, actionable, status)
+ except (KeyError, TypeError, ValueError, RuntimeError, httpx.HTTPError) as error:
+ return Review(check, "unavailable", None, f"Review unavailable: {error}", False, "error")
+
+
+def review_question(question: str, schema: str, metric_definitions: list[str]) -> Review:
+ return _choice_review(
+ check="question clarity",
+ state={"question": question, "database_schema": schema, "known_metric_definitions": metric_definitions},
+ verdicts={
+ "clear": "The question has enough information to answer from this schema and known definitions.",
+ "clarify": "An essential definition is missing; answering would require a material assumption.",
+ },
+ issues={
+ "none": "No essential definition is missing.",
+ "metric_definition": "Clarify how the requested metric should be calculated.",
+ "time_range": "Clarify the required time range.",
+ "population": "Clarify which records or population should be included.",
+ "comparison": "Clarify the comparison or grouping requested.",
+ },
+ actionable_verdict="clarify",
+ )
+
+
+def review_answer(question: str, sql: str, rows: list[dict[str, Any]], answer: str) -> Review:
+ return _choice_review(
+ check="answer grounding",
+ state={"question": question, "executed_sql": sql, "returned_rows": rows, "answer": answer},
+ verdicts={
+ "grounded": "Every material factual claim in the answer is supported by the SQL result rows.",
+ "mismatch": "At least one material factual claim is not supported by the SQL result rows.",
+ },
+ issues={
+ "none": "The answer is supported by the returned rows.",
+ "unsupported_value": "A reported value is not supported by the returned rows.",
+ "unsupported_comparison": "A comparison or ranking is not supported by the returned rows.",
+ "unsupported_scope": "The answer claims a broader scope than the returned rows support.",
+ "missing_limitation": "The answer omits a limitation that materially changes its meaning.",
+ },
+ actionable_verdict="mismatch",
+ )
diff --git a/ai_agents/nl_data_analyst_agent/main.py b/ai_agents/nl_data_analyst_agent/main.py
index 5c9ab4d..357010b 100644
--- a/ai_agents/nl_data_analyst_agent/main.py
+++ b/ai_agents/nl_data_analyst_agent/main.py
@@ -14,13 +14,16 @@ import httpx
import pandas as pd
from dotenv import load_dotenv
+load_dotenv()
+
+from jev_review import Review, review_answer, review_question
from seed_data import seed_database
-load_dotenv()
ROOT = Path(__file__).resolve().parent
DEMO_DATABASE = ROOT / "data" / "demo.sqlite"
REGISTRY = ROOT / "data" / "connections.json"
EVE_URL = os.getenv("EVE_URL", "http://127.0.0.1:3000").rstrip("/")
+DEMO_METRICS = ["completed-order revenue = quantity * unit_price for orders where status = 'completed'"]
def schema_text(path: Path) -> str:
@@ -76,8 +79,95 @@ def eve_post(path: str, payload: dict[str, Any]) -> dict[str, Any]:
return response.json()
-def consume_events(session: dict[str, Any]) -> tuple[str, str, pd.DataFrame, dict[str, Any] | None]:
- answer, sql, rows, pending = "", "", pd.DataFrame(), None
+def present_grounding_review(answer: str, grounding: Review) -> tuple[str, str | None]:
+ if grounding.actionable:
+ return (
+ f"⚠️ **Unverified draft — awaiting user review.** {grounding.message()}\n\n"
+ "The explanation below is not treated as final. Compare it with the displayed rows, or submit: "
+ "“Revise the previous answer using only the displayed SQL rows and explicitly correct unsupported claims.”\n\n"
+ f"**Eve draft (unverified):**\n\n{answer}",
+ None,
+ )
+ if grounding.status != "ok":
+ return answer, grounding.message() + " The answer is shown because uncertain or failed reviews do not block it."
+ return answer, None
+
+
+def project_eve_events(
+ events: list[dict[str, Any]], question: str, focus_call_id: str | None = None,
+) -> tuple[str, str, pd.DataFrame, dict[str, Any] | None]:
+ answer, pending = "", None
+ proposed_sql: dict[str, str] = {}
+ completed: dict[str, dict[str, Any]] = {}
+ completed_order: list[str] = []
+ sql_reviews: list[Review] = []
+ for event in events:
+ kind, data = event.get("type"), event.get("data") or {}
+ if kind == "actions.requested":
+ for action in data.get("actions", []):
+ if action.get("toolName", "").endswith("run_sql"):
+ call_id = action.get("callId")
+ sql = action.get("input", {}).get("sql")
+ if call_id and isinstance(sql, str):
+ proposed_sql[call_id] = sql
+ elif kind == "action.result":
+ result = data.get("result") or {}
+ output = result.get("output") or {}
+ call_id = result.get("callId")
+ if isinstance(output, dict):
+ sql = output.get("sql") or proposed_sql.get(call_id, "")
+ if call_id and "rows" in output:
+ completed[call_id] = {
+ "callId": call_id,
+ "sql": sql,
+ "rows": output["rows"],
+ }
+ if call_id not in completed_order:
+ completed_order.append(call_id)
+ review = output.get("review")
+ if isinstance(review, dict) and (review.get("actionable") or review.get("status") != "ok"):
+ sql_reviews.append(Review(**review))
+ elif kind == "input.requested":
+ for request in data.get("requests") or []:
+ action = request.get("action") or {}
+ if request.get("kind") == "tool-approval" and action.get("toolName", "").endswith("run_sql"):
+ call_id = action.get("callId")
+ sql = action.get("input", {}).get("sql") or proposed_sql.get(call_id, "")
+ pending = {"requestId": request["requestId"], "callId": call_id, "sql": sql}
+ break
+ elif kind == "message.completed" and data.get("finishReason") != "tool-calls":
+ answer = data.get("message") or answer
+ elif kind in {"turn.failed", "session.failed"}:
+ answer = f"Eve could not complete this question: {data.get('message', 'Unknown error')}"
+
+ selected: dict[str, Any] | None = None
+ if pending:
+ prior_ids = [call_id for call_id in completed_order if call_id != pending.get("callId")]
+ if prior_ids:
+ pending["priorCompleted"] = completed[prior_ids[-1]]
+ sql = pending.get("sql", "")
+ rows = pd.DataFrame()
+ else:
+ selected_id = focus_call_id if focus_call_id in completed else (completed_order[-1] if completed_order else None)
+ selected = completed.get(selected_id) if selected_id else None
+ sql = selected.get("sql", "") if selected else ""
+ rows = pd.DataFrame(selected.get("rows", [])) if selected else pd.DataFrame()
+
+ notes = [review.message() for review in sql_reviews]
+ if answer and sql and not pending:
+ grounding = review_answer(question, sql, rows.to_dict(orient="records"), answer)
+ answer, grounding_note = present_grounding_review(answer, grounding)
+ if grounding_note:
+ notes.append(grounding_note)
+ if notes:
+ answer = answer + ("\n\n" if answer else "") + "\n\n".join(f"> {note}" for note in notes)
+ return answer, sql, rows, pending
+
+
+def consume_events(
+ session: dict[str, Any], question: str, focus_call_id: str | None = None,
+) -> tuple[str, str, pd.DataFrame, dict[str, Any] | None]:
+ events: list[dict[str, Any]] = []
with httpx.Client(timeout=httpx.Timeout(15, read=180)) as client:
with client.stream("GET", EVE_URL + f"/eve/v1/session/{session['id']}/stream",
params={"startIndex": session["cursor"]}) as response:
@@ -87,27 +177,10 @@ def consume_events(session: dict[str, Any]) -> tuple[str, str, pd.DataFrame, dic
continue
event = json.loads(line)
session["cursor"] += 1
- kind, data = event.get("type"), event.get("data") or {}
- if kind == "actions.requested":
- for action in data.get("actions", []):
- if action.get("toolName", "").endswith("run_sql"):
- sql = action.get("input", {}).get("sql", sql)
- elif kind == "action.result":
- output = (data.get("result") or {}).get("output") or {}
- if isinstance(output, dict) and "rows" in output:
- rows = pd.DataFrame(output["rows"])
- sql = output.get("sql", sql)
- elif kind == "input.requested":
- requests = data.get("requests") or []
- if requests:
- pending = {"requestId": requests[0]["requestId"]}
- elif kind == "message.completed" and data.get("finishReason") != "tool-calls":
- answer = data.get("message") or answer
- elif kind in {"turn.failed", "session.failed"}:
- answer = f"Eve could not complete this question: {data.get('message', 'Unknown error')}"
- elif kind == "session.waiting":
+ events.append(event)
+ if event.get("type") == "session.waiting":
break
- return answer, sql, rows, pending
+ return project_eve_events(events, question, focus_call_id)
def ask(question: str, chat: list[dict[str, str]], pending: dict[str, Any] | None,
@@ -119,17 +192,33 @@ def ask(question: str, chat: list[dict[str, str]], pending: dict[str, Any] | Non
if not question.strip():
return chat, "", "", pd.DataFrame(), None, session, gr.update(visible=False), gr.update(visible=False)
chat = chat + [{"role": "user", "content": question.strip()}]
+ schema = schema_text(Path(json.loads(REGISTRY.read_text())[database_id]))
+ clarity = review_question(question.strip(), schema, DEMO_METRICS if database_id == "demo" else [])
+ if clarity.actionable:
+ chat.append({"role": "assistant", "content": clarity.message() + " Please clarify that point, then submit the question again."})
+ return chat, question, "", pd.DataFrame(), None, session, gr.update(visible=False), gr.update(visible=False)
try:
message = f"Database ID: {database_id}\nQuestion: {question.strip()}"
if session is None:
created = eve_post("/eve/v1/session", {"message": message})
- session = {"id": created["sessionId"], "cursor": 0}
+ session = {"id": created["sessionId"], "cursor": 0, "question": question.strip()}
else:
eve_post(f"/eve/v1/session/{session['id']}", {"message": message})
- answer, sql, rows, pending = consume_events(session)
- chat.append({"role": "assistant", "content": (
+ session["question"] = question.strip()
+ answer, sql, rows, pending = consume_events(session, question.strip())
+ if clarity.status != "ok":
+ answer = (answer + "\n\n" if answer else "") + f"> {clarity.message()} The question proceeded because this review was not confident."
+ content = (
"This query needs approval before Eve runs it. Review the SQL and choose Approve or Reject."
- if pending else answer or "Eve returned no answer. Check its terminal for details.")})
+ if pending else answer or "Eve returned no answer. Check its terminal for details.")
+ if pending and pending.get("priorCompleted"):
+ content += (
+ "\n\nA different SQL call completed in the same turn. Its rows are hidden while you review "
+ "the SQL awaiting approval and will be restored with a clear label if you reject it."
+ )
+ if pending and clarity.status != "ok":
+ content += f"\n\n> {clarity.message()} The question proceeded because this review was not confident."
+ chat.append({"role": "assistant", "content": content})
return chat, "", sql, rows, pending, session, gr.update(visible=bool(pending)), gr.update(visible=bool(pending))
except (httpx.HTTPError, OSError, ValueError) as error:
chat.append({"role": "assistant", "content": f"Could not reach Eve: {error}. Check the Eve server and gateway key."})
@@ -142,8 +231,19 @@ def decide(approved: bool, chat: list[dict[str, str]], pending: dict[str, Any] |
raise gr.Error("No query is waiting for approval.")
try:
eve_post(f"/eve/v1/session/{session['id']}", {"inputResponses": [{"requestId": pending["requestId"],
- "optionId": "approve" if approved else "deny"}]})
- answer, sql, rows, next_pending = consume_events(session)
+ "optionId": "approve" if approved else "cancel"}]})
+ answer, sql, rows, next_pending = consume_events(
+ session, session.get("question", ""), focus_call_id=pending.get("callId"),
+ )
+ if not approved and not next_pending and pending.get("priorCompleted"):
+ prior = pending["priorCompleted"]
+ sql = prior.get("sql", "")
+ rows = pd.DataFrame(prior.get("rows", []))
+ label = (
+ "The displayed SQL and rows belong to an earlier completed query "
+ f"(`{prior.get('callId', 'unknown call')}`), not the rejected query."
+ )
+ answer = answer + ("\n\n" if answer else "") + label
chat = chat + [{"role": "assistant", "content": answer or ("Query rejected." if not approved else "Eve returned no answer.")}]
return chat, sql, rows, next_pending, session, gr.update(visible=bool(next_pending)), gr.update(visible=bool(next_pending))
except (httpx.HTTPError, OSError, ValueError) as error:
diff --git a/ai_agents/nl_data_analyst_agent/package.json b/ai_agents/nl_data_analyst_agent/package.json
index 7c3fd68..424140f 100644
--- a/ai_agents/nl_data_analyst_agent/package.json
+++ b/ai_agents/nl_data_analyst_agent/package.json
@@ -4,7 +4,8 @@
"type": "module",
"scripts": {
"build": "node node_modules/eve/bin/eve.js build",
- "dev": "node --env-file=.env scripts/start_local.mjs"
+ "dev": "node --env-file=.env scripts/start_local.mjs",
+ "test": "node --test tests/jev.test.ts"
},
"dependencies": {
"ai": "^7.0.105",
diff --git a/ai_agents/nl_data_analyst_agent/tests/jev.test.ts b/ai_agents/nl_data_analyst_agent/tests/jev.test.ts
new file mode 100644
index 0000000..acbe70c
--- /dev/null
+++ b/ai_agents/nl_data_analyst_agent/tests/jev.test.ts
@@ -0,0 +1,71 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { reviewSqlRelevance } from "../agent/lib/jev.ts";
+import { boundQuestionFor, parseAnalystMessage } from "../agent/lib/question_context.ts";
+
+function evaluator(verdict: "relevant" | "mismatch", confidence: number, issue: string) {
+ return async () => ({
+ answers: {
+ verdict: { type: "choice", choice: verdict, confidence, probabilities: {} },
+ issue: { type: "choice", choice: issue, confidence: 0.9, probabilities: {} },
+ },
+ }) as any;
+}
+
+const state = {
+ question: "Which region has the most revenue?",
+ sql: "SELECT region, SUM(total) FROM orders GROUP BY region",
+ databaseSchema: [{ table: "orders", columns: [{ name: "region", type: "TEXT" }] }],
+};
+
+test("relevant SQL proceeds", async () => {
+ const review = await reviewSqlRelevance(state, evaluator("relevant", 0.94, "none"));
+ assert.equal(review.actionable, false);
+ assert.equal(review.status, "ok");
+});
+
+test("confident SQL mismatch blocks execution with a revision reason", async () => {
+ const review = await reviewSqlRelevance(state, evaluator("mismatch", 0.91, "wrong_metric"));
+ assert.equal(review.actionable, true);
+ assert.match(review.issue, /different metric/i);
+});
+
+test("low-confidence SQL mismatch proceeds", async () => {
+ const review = await reviewSqlRelevance(state, evaluator("mismatch", 0.30, "wrong_filter"));
+ assert.equal(review.actionable, false);
+ assert.equal(review.status, "low_confidence");
+});
+
+test("Jev failure proceeds without authorizing anything", async () => {
+ const review = await reviewSqlRelevance(state, (async () => { throw new Error("offline"); }) as any);
+ assert.equal(review.actionable, false);
+ assert.equal(review.status, "error");
+});
+
+test("SQL review question is bound to the authoritative Eve turn message", () => {
+ const binding = parseAnalystMessage(
+ "Database ID: demo\nQuestion: Which region has the most completed-order revenue?",
+ "turn_7",
+ );
+ assert.equal(
+ boundQuestionFor(binding, "demo", "turn_7"),
+ "Which region has the most completed-order revenue?",
+ );
+ assert.throws(() => boundQuestionFor(binding, "demo", "turn_spoofed"), /not bound/);
+ assert.throws(() => boundQuestionFor(binding, "other", "turn_7"), /not bound/);
+});
+
+test("mismatch without an issue is inconclusive and does not block", async () => {
+ const review = await reviewSqlRelevance(state, evaluator("mismatch", 0.96, "none"));
+ assert.equal(review.status, "inconsistent");
+ assert.equal(review.actionable, false);
+ assert.match(review.issue, /inconclusive/i);
+});
+
+test("relevant verdict ignores a contradictory mismatch issue", async () => {
+ const review = await reviewSqlRelevance(state, evaluator("relevant", 0.96, "wrong_metric"));
+ assert.equal(review.status, "inconsistent");
+ assert.equal(review.actionable, false);
+ assert.equal(review.issue, "The SQL addresses the question.");
+});
diff --git a/ai_agents/nl_data_analyst_agent/tests/test_jev_review.py b/ai_agents/nl_data_analyst_agent/tests/test_jev_review.py
new file mode 100644
index 0000000..7ff4b07
--- /dev/null
+++ b/ai_agents/nl_data_analyst_agent/tests/test_jev_review.py
@@ -0,0 +1,91 @@
+"""Offline Jev contract tests. No model calls are made."""
+
+from __future__ import annotations
+
+import jev_review
+
+
+def response(verdict: str, confidence: float, issue: str) -> dict:
+ return {
+ "answers": {
+ "verdict": {"type": "choice", "choice": verdict, "confidence": confidence},
+ "issue": {"type": "choice", "choice": issue, "confidence": 0.9},
+ }
+ }
+
+
+def test_clear_question_is_not_blocked(monkeypatch) -> None:
+ monkeypatch.setattr(jev_review, "_post_jev", lambda _: response("clear", 0.93, "none"))
+ review = jev_review.review_question("Revenue by region?", "orders: region TEXT", ["revenue = quantity * unit_price"])
+ assert review.verdict == "clear"
+ assert review.confidence == 0.93
+ assert not review.actionable
+
+
+def test_unclear_question_requests_clarification(monkeypatch) -> None:
+ monkeypatch.setattr(jev_review, "_post_jev", lambda _: response("clarify", 0.91, "metric_definition"))
+ review = jev_review.review_question("Which customer is best?", "customers: id INTEGER", [])
+ assert review.actionable
+ assert "metric" in review.issue.lower()
+
+
+def test_answer_grounding_mismatch_provides_review_path(monkeypatch) -> None:
+ monkeypatch.setattr(jev_review, "_post_jev", lambda _: response("mismatch", 0.88, "unsupported_value"))
+ review = jev_review.review_answer("How many?", "SELECT count(*) AS n FROM orders", [{"n": 4}], "There are 9.")
+ assert review.actionable
+ assert review.verdict == "mismatch"
+ assert "value" in review.issue.lower()
+
+
+def test_low_confidence_never_blocks(monkeypatch) -> None:
+ monkeypatch.setattr(jev_review, "_post_jev", lambda _: response("clarify", 0.42, "time_range"))
+ review = jev_review.review_question("Revenue?", "orders: created_at TEXT", [])
+ assert review.status == "low_confidence"
+ assert not review.actionable
+
+
+def test_api_failure_never_blocks(monkeypatch) -> None:
+ def fail(_):
+ raise RuntimeError("offline")
+
+ monkeypatch.setattr(jev_review, "_post_jev", fail)
+ review = jev_review.review_answer("How many?", "SELECT 1", [{"1": 1}], "One")
+ assert review.status == "error"
+ assert review.verdict == "unavailable"
+ assert not review.actionable
+
+
+def test_settings_are_read_at_request_time(monkeypatch) -> None:
+ captured = {}
+
+ def fake_post(payload):
+ captured["payload"] = payload
+ captured["url"] = jev_review.jev_url()
+ return response("clear", 0.75, "none")
+
+ monkeypatch.setenv("JEV_MODEL", "typesafe-ai/custom-jev")
+ monkeypatch.setenv("JEV_URL", "https://example.test/v1/evaluate")
+ monkeypatch.setenv("JEV_MIN_CONFIDENCE", "0.80")
+ monkeypatch.setattr(jev_review, "_post_jev", fake_post)
+
+ review = jev_review.review_question("How many orders?", "orders: id INTEGER", [])
+
+ assert captured["payload"]["model"] == "typesafe-ai/custom-jev"
+ assert captured["url"] == "https://example.test/v1/evaluate"
+ assert review.status == "low_confidence"
+
+
+def test_actionable_verdict_without_issue_is_inconclusive(monkeypatch) -> None:
+ monkeypatch.setattr(jev_review, "_post_jev", lambda _: response("clarify", 0.95, "none"))
+ review = jev_review.review_question("Best customer?", "customers: id INTEGER", [])
+ assert review.status == "inconsistent"
+ assert not review.actionable
+ assert "inconclusive" in review.issue
+
+
+def test_non_actionable_verdict_ignores_conflicting_issue(monkeypatch) -> None:
+ monkeypatch.setattr(jev_review, "_post_jev", lambda _: response("grounded", 0.95, "unsupported_value"))
+ review = jev_review.review_answer("How many?", "SELECT 4", [{"n": 4}], "There are four.")
+ assert review.status == "inconsistent"
+ assert not review.actionable
+ assert review.issue == "The answer is supported by the returned rows."
diff --git a/ai_agents/nl_data_analyst_agent/tests/test_ui.py b/ai_agents/nl_data_analyst_agent/tests/test_ui.py
index 7a488a1..dbb56ea 100644
--- a/ai_agents/nl_data_analyst_agent/tests/test_ui.py
+++ b/ai_agents/nl_data_analyst_agent/tests/test_ui.py
@@ -6,6 +6,7 @@ from pathlib import Path
import pytest
import main
+from jev_review import Review
from seed_data import seed_database
@@ -45,3 +46,149 @@ def test_demo_button_creates_database(tmp_path: Path, monkeypatch: pytest.Monkey
def test_question_requires_connection() -> None:
with pytest.raises(Exception, match="Connect a SQLite database"):
main.ask("How many orders?", [], None, None, None)
+
+
+def test_clarification_happens_before_eve(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ database = tmp_path / "demo.sqlite"
+ seed_database(database)
+ registry = tmp_path / "connections.json"
+ registry.write_text(json.dumps({"demo": str(database)}))
+ monkeypatch.setattr(main, "REGISTRY", registry)
+ monkeypatch.setattr(main, "review_question", lambda *_: Review(
+ "question clarity", "clarify", 0.94, "Clarify how the requested metric should be calculated.", True
+ ))
+ monkeypatch.setattr(main, "eve_post", lambda *_: pytest.fail("Eve must not receive an unclear question"))
+
+ chat, retained_question, sql, results, pending, session, approve, reject = main.ask(
+ "Who is best?", [], None, "demo", None
+ )
+
+ assert retained_question == "Who is best?"
+ assert "Please clarify" in chat[-1]["content"]
+ assert sql == "" and results.empty and pending is None and session is None
+ assert not approve["visible"] and not reject["visible"]
+
+
+def test_grounding_mismatch_is_clearly_unverified() -> None:
+ review = Review(
+ "answer grounding", "mismatch", 0.96,
+ "A reported value is not supported by the returned rows.", True,
+ )
+ displayed, note = main.present_grounding_review("Revenue was $900.", review)
+ assert displayed.startswith("⚠️ **Unverified draft — awaiting user review.**")
+ assert "not treated as final" in displayed
+ assert "Revise the previous answer" in displayed
+ assert "**Eve draft (unverified):**" in displayed
+ assert note is None
+
+
+def test_batched_sql_calls_do_not_mix_completed_rows_with_pending_approval(monkeypatch) -> None:
+ revenue_call = "call_revenue"
+ metadata_call = "call_metadata"
+ revenue_sql = "SELECT region, SUM(revenue) AS revenue FROM orders WHERE year = 2025 GROUP BY region"
+ metadata_sql = "SELECT MIN(order_date), MAX(order_date), COUNT(*) FROM orders"
+ events = [
+ {"type": "actions.requested", "data": {"actions": [
+ {"callId": revenue_call, "toolName": "run_sql", "input": {"databaseId": "demo", "sql": revenue_sql}},
+ ]}},
+ {"type": "actions.requested", "data": {"actions": [
+ {"callId": metadata_call, "toolName": "run_sql", "input": {"databaseId": "demo", "sql": metadata_sql}},
+ ]}},
+ {"type": "action.result", "data": {"result": {
+ "callId": revenue_call,
+ "toolName": "run_sql",
+ "output": {
+ "sql": revenue_sql,
+ "rows": [{"region": "South", "revenue": 98664}],
+ "review": {
+ "check": "SQL relevance", "verdict": "relevant", "confidence": 0.95,
+ "issue": "The SQL addresses the question.", "actionable": False, "status": "ok",
+ },
+ "execution": "completed",
+ },
+ }}},
+ {"type": "input.requested", "data": {"requests": [{
+ "requestId": "request_metadata",
+ "kind": "tool-approval",
+ "action": {
+ "callId": metadata_call,
+ "toolName": "run_sql",
+ "input": {"databaseId": "demo", "sql": metadata_sql},
+ },
+ }]}},
+ {"type": "session.waiting", "data": {}},
+ ]
+
+ monkeypatch.setattr(main, "review_answer", lambda *_: pytest.fail("Pending calls are not grounded"))
+ answer, displayed_sql, displayed_rows, pending = main.project_eve_events(
+ events, "Which region had the most completed-order revenue in 2025?",
+ )
+
+ assert answer == ""
+ assert displayed_sql == metadata_sql
+ assert displayed_rows.empty
+ assert pending == {
+ "requestId": "request_metadata",
+ "callId": metadata_call,
+ "sql": metadata_sql,
+ "priorCompleted": {
+ "callId": revenue_call,
+ "sql": revenue_sql,
+ "rows": [{"region": "South", "revenue": 98664}],
+ },
+ }
+
+
+def test_approved_call_selects_only_its_matching_result(monkeypatch) -> None:
+ monkeypatch.setattr(
+ main,
+ "review_answer",
+ lambda *_: Review("answer grounding", "grounded", 0.95, "Supported.", False),
+ )
+ events = [
+ {"type": "action.result", "data": {"result": {
+ "callId": "call_other", "toolName": "run_sql",
+ "output": {"sql": "SELECT 1 AS n", "rows": [{"n": 1}]},
+ }}},
+ {"type": "action.result", "data": {"result": {
+ "callId": "call_approved", "toolName": "run_sql",
+ "output": {"sql": "SELECT 2 AS n", "rows": [{"n": 2}]},
+ }}},
+ {"type": "message.completed", "data": {"message": "The approved query returned 2.", "finishReason": "stop"}},
+ ]
+
+ _, displayed_sql, displayed_rows, pending = main.project_eve_events(
+ events, "Return the approved value", focus_call_id="call_approved",
+ )
+
+ assert displayed_sql == "SELECT 2 AS n"
+ assert displayed_rows.to_dict(orient="records") == [{"n": 2}]
+ assert pending is None
+
+
+def test_rejection_restores_prior_result_with_a_clear_label(monkeypatch) -> None:
+ sent = {}
+ prior = {"callId": "call_revenue", "sql": "SELECT revenue FROM totals", "rows": [{"revenue": 98664}]}
+ pending = {
+ "requestId": "request_metadata",
+ "callId": "call_metadata",
+ "sql": "SELECT COUNT(*) FROM orders",
+ "priorCompleted": prior,
+ }
+ monkeypatch.setattr(main, "eve_post", lambda path, payload: sent.update(path=path, payload=payload))
+ monkeypatch.setattr(
+ main,
+ "consume_events",
+ lambda session, question, focus_call_id=None: ("Query rejected.", "", main.pd.DataFrame(), None),
+ )
+
+ chat, sql, rows, next_pending, *_ = main.decide(
+ False, [], pending, {"id": "session_1", "cursor": 4, "question": "Revenue?"},
+ )
+
+ assert sent["payload"]["inputResponses"][0]["optionId"] == "cancel"
+ assert sql == prior["sql"]
+ assert rows.to_dict(orient="records") == prior["rows"]
+ assert next_pending is None
+ assert "earlier completed query" in chat[-1]["content"]
+ assert "not the rejected query" in chat[-1]["content"]