add all files

This commit is contained in:
Rucus
2026-02-17 09:29:34 -06:00
parent b8c8d67c67
commit 782d203799
21925 changed files with 2433086 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
# Copilot Instructions
## Repo Orientation
- Two main toolkits live here: SQL agents in `db_agent/` and `cane_agent/`, plus an anomaly detection pipeline in `anomaly_detection/`.
- `cane_agent/` mirrors `db_agent/`; when altering shared logic, update both (or refactor to a shared module) to keep behavior aligned.
- Context artifacts (`context/`), prompts (`prompting/`), CLIs, and UI layers sit beside each agent for easy packaging.
## SQL Agent (db_agent/, cane_agent/)
- `prompting/prompt_builder.py` loads `context/schema.json`, `glossary.md`, `value_hints.yaml`, and `examples.json` to build the single LLM prompt; pass `table_hints` to shrink the schema section.
- `client.SqlAgentClient` wraps the TGI endpoint (`LlmConfig.base_url`), retries once with a strict formatting reminder, strips unrequested timeframe filters, and normalizes syntax (e.g., removes `ILIKE`, `NULLS LAST`).
- `sql_executor.py` enforces read-only T-SQL: it rejects multi-statements, dangerous verbs, and non-SQL Server constructs, then injects `TOP (max_rows)` before execution.
- DB credentials come from env vars (`DB_SERVER`, `DB_DATABASE`, `DB_USERNAME`, `DB_PASSWORD`) defined via `extractor/settings.DbSettings`; missing vars raise immediately.
- Logs append to `logs/query_log.jsonl` through `log_utils.log_interaction`, capturing sanitized SQL, warnings, and optional feedback tags.
## SQL Agent Workflows
- Install deps in a venv: `python -m venv .venv; .\.venv\Scripts\Activate.ps1; pip install -r db_agent/requirements.txt` (repeat for `anomaly_detection` if needed).
- Dot-source `db_agent/scripts/Set-DbEnv.ps1` to export `DB_SERVER`, `DB_DATABASE`, `DB_USERNAME`, `DB_PASSWORD`, and related flags in one step; the script prompts for the password if you omit `-Password`.
- Refresh schema context with `python -m db_agent.extractor --job schema --schema dbo --output db_agent/context/schema.json`; adjust module name for `cane_agent`.
- Run ad hoc questions via `python -m db_agent.run_agent "How many loads closed yesterday?" --tables dbo.SugarLoadData --execute --max-rows 200`.
- Serve the UI with `uvicorn db_agent.ui.backend.main:app --reload --host 0.0.0.0 --port 8000`; the backend lazily instantiates `default_client()` and reuses the same logging path.
- TGI must be up (see `deployment/docker-compose.yml`); model responses are expected at `<base_url>/generate` returning `generated_text` JSON.
- Set `UI_BASIC_USER`/`UI_BASIC_PASSWORD` to force HTTP Basic auth on the UI/API; leave unset for local testing. `/health` stays unauthenticated.
## Anomaly Detection (anomaly_detection/)
- `data_loader.load_timeseries` standardizes CSV ingestion, sorts by timestamp, retains ID columns, and stashes inferred features in `df.attrs["feature_columns"]` for downstream reuse.
- `feature_engineering.build_feature_matrix` is the single gateway for rolling statistics and rate-of-change features; supply `rolling_windows` in pandas offset notation (`5T`, `15T`, `60T`).
- `train.py` builds a `StandardScaler` + `IsolationForest` pipeline, persists artifacts under `ml/anomaly_detection/models/`, and writes training scores to `ml/anomaly_detection/outputs/`.
- `detect.py` reloads the artifact, rehydrates feature engineering flags, and enforces feature parity before scoring; `--keep-features`, `--alert-threshold`, and `--top-n` control outputs and diagnostics.
## Conventions & Tips
- PowerShell examples use caret continuations; mirror that style when documenting multi-line commands.
- Prefer pandas-native operations and avoid mutating inputs in place—helpers copy before augmentation.
- When extending SQL safety rules or prompt shaping, add the change in both agent copies and keep JSON-only responses from the model (`{"sql": ..., "summary": ...}`).
- No automated tests ship with the repo; verify changes by running the CLIs/UI with representative CSVs and MSSQL connections, and check the JSONL logs for regressions.

View File

@@ -0,0 +1,35 @@
# Copilot Instructions
## Project Overview
- Repo covers a lightweight unsupervised anomaly detection pipeline focused on historian CSV exports.
- Core package lives in `src/`; CLI entry points `train.py` and `detect.py` orchestrate data prep, feature engineering, and model scoring.
- `requirements.txt` pins analytics stack (`pandas`, `scikit-learn`, `numpy`, `joblib`)—assume Python 3.10+ with virtualenv per README.
## Data Loading & Validation
- Reuse `src/data_loader.py::load_timeseries` with `DataLoadConfig` to ensure consistent timestamp parsing, optional timezone localization, and feature inference.
- When adding new ingestion logic, funnel it through `load_timeseries` or extend it; downstream code relies on `df.attrs["feature_columns"]` being populated for inference overrides.
- Raise `DataValidationError` for user-facing data issues instead of generic exceptions so CLIs can surface clear messages.
## Feature Engineering Patterns
- `feature_engineering.build_feature_matrix` is the single entry point for derived features; it controls rolling stats (`add_rolling_statistics`) and rate-of-change (`add_rate_of_change`).
- Rolling windows are expressed with pandas offset aliases (default `5T`, `15T`, `60T`); keep new feature names suffix-based so persisted artifacts stay discoverable.
- Always pass through `timestamp_column` and any `id_columns`; the helper filters non-numeric fields automatically.
## Training Workflow (`src/train.py`)
- CLI expects PowerShell-friendly invocation (`^` line continuations) and creates artifact bundles with pipeline + metadata.
- `fit_pipeline` wraps `StandardScaler` + `IsolationForest` with configurable contamination, estimators, and random-state—extend via the existing Pipeline to avoid breaking saved artifacts.
- `generate_scores` writes anomaly flags plus ranking; extra columns must come from the non-feature portion of `feature_df`.
- Outputs default to `ml/anomaly_detection/models/` and `ml/anomaly_detection/outputs/`; use `ensure_parent_dir` before writing new files.
## Detection Workflow (`src/detect.py`)
- Loads the joblib artifact and rehydrates config (rolling flags, windows) when building features; keep artifact schema stable across changes.
- Supports overrides for timestamp, features, and id columns—mirror option names if adding parameters to maintain parity with training CLI.
- `--keep-features` toggles whether engineered columns are retained in the scored CSV; preserve this pattern when expanding outputs.
- If you add new anomaly criteria, integrate with the existing `alert_threshold` / `top_n` flow instead of inventing parallel mechanisms.
## Project Conventions & Tips
- Scripts use local imports (e.g., `from data_loader import ...`); when creating new modules keep them under `src/` and import similarly to run via `python ml/anomaly_detection/src/<script>.py`.
- Favor pandas-native operations and avoid mutating input frames in place—helpers copy data before augmentation.
- Gracefully handle timezone-aware timestamps by checking dtype (`pandas.api.types`) as done in feature helpers.
- There are no bundled tests; when adding features, demonstrate usage via docstrings or README snippets and validate with small CSV fixtures.
- Readme commands assume Windows PowerShell; prefer caret continuations and backslash paths when documenting new CLI usage.

View File

@@ -0,0 +1,75 @@
# Anomaly Detection Starter Kit
This module seeds a machine-learning workflow for flagging unusual behavior in LASUCA's process data (steam flow, turbine RPM, conveyor load cells, etc.). It focuses on unsupervised anomaly detection so you can start surfacing outliers without labeled fault data.
## Project structure
```
ml/anomaly_detection/
├── README.md # Project overview and next steps
├── requirements.txt # Python dependencies for the pipeline
└── src/
├── __init__.py # Marks the package
├── data_loader.py # Helpers for reading & validating time-series data
├── feature_engineering.py # Domain feature transformations and rolling stats
├── train.py # CLI script to fit an Isolation Forest model
└── detect.py # CLI script to score new data with the trained model
```
## Quick start
1. **Create a virtual environment** inside the repository root and install dependencies:
```powershell
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r ml/anomaly_detection/requirements.txt
```
2. **Prepare a CSV export** with at least the following columns:
- `timestamp`: ISO 8601 timestamp or anything `pandas.to_datetime` can parse.
- Sensor columns: numerical fields such as `steam_tph`, `turbine_rpm`, `conveyor_tph`.
Additional metadata columns (e.g., `area`, `equipment`) are optional and help slice metrics later.
3. **Train a baseline model**:
```powershell
python ml/anomaly_detection/src/train.py ^
--data data/clean/process_snapshot.csv ^
--timestamp-column timestamp ^
--features steam_tph turbine_rpm conveyor_tph ^
--model-out ml/anomaly_detection/models/isolation_forest.joblib
```
The script standardizes numeric columns, fits an Isolation Forest, and saves the pipeline along with a CSV of anomaly scores.
4. **Score fresh data** (e.g., streaming batch or another day):
```powershell
python ml/anomaly_detection/src/detect.py ^
--data data/clean/process_snapshot_new.csv ^
--model ml/anomaly_detection/models/isolation_forest.joblib ^
--timestamp-column timestamp ^
--features steam_tph turbine_rpm conveyor_tph ^
--output data/clean/process_snapshot_new_scored.csv
```
## Roadmap ideas
| Phase | Goal | Details |
|-------|------|---------|
| Baseline | Clean data + isolation forest | Validate signals, calculate rolling mean/std, track top anomalies per asset & shift. |
| Enhancements | Context-aware detection | Separate models per unit (boiler, milling line), include load-based normalization, add feedback loop for dismissed alerts. |
| Advanced | Forecast + residual alerts | Train LSTM/Prophet forecasts and alert on residuals, integrate maintenance work orders. |
## Data tips
- **Resample** fast signals to a consistent cadence (e.g., 1 min) to smooth control jitter.
- **Align units** (e.g., convert all steam flows to TPH) before feeding models.
- **Label known events** (downs, maintenance) to benchmark the detector and reduce false positives.
## Next steps
1. Pull a week of reconciled historian data into `data/clean/`.
2. Run `train.py` to create an initial anomaly score CSV.
3. Visualize results in the existing dashboards or a Jupyter notebook (e.g., scatter of anomaly score vs. timestamp grouped by equipment).
4. Iterate on feature engineering: rolling gradients, energy-per-ton, turbine slip ratios, etc.
5. Deploy: schedule the detection script (cron/Windows Task Scheduler) and push alerts via email or dashboard badges.
Feel free to extend the pipeline with deep-learning models, model registry integration, or streaming inferencing as the project matures.

View File

@@ -0,0 +1,7 @@
pandas>=2.1,<3.0
numpy>=1.24,<3.0
scikit-learn>=1.4,<2.0
joblib>=1.3,<2.0
matplotlib>=3.8,<4.0
seaborn>=0.13,<1.0
pyyaml>=6.0,<7.0

View File

@@ -0,0 +1 @@
"""Anomaly detection toolkit for LASUCA controls data."""

View File

@@ -0,0 +1,104 @@
"""Utilities for loading and validating historian exports.
The goal is to keep data ingestion consistent across training and
inference flows. Functions here assume CSV input but can be expanded to
support SQL queries or APIs later.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable, List, Optional, Sequence
import pandas as pd
@dataclass
class DataLoadConfig:
"""Configuration describing the structure of the raw dataset."""
timestamp_column: str
feature_columns: Optional[Sequence[str]] = None
id_columns: Sequence[str] = ()
dropna: bool = True
timezone: Optional[str] = None
class DataValidationError(RuntimeError):
"""Raised when the provided dataset cannot be prepared as requested."""
def _normalize_columns(columns: Iterable[str]) -> List[str]:
return [str(col) for col in columns]
def load_timeseries(csv_path: Path, config: DataLoadConfig) -> pd.DataFrame:
"""Load and clean a historian export.
Parameters
----------
csv_path:
Path to the CSV file to read.
config:
DataLoadConfig describing timestamp and required feature columns.
Returns
-------
pandas.DataFrame
Sorted dataframe with parsed timestamps and selected columns.
"""
csv_path = Path(csv_path)
if not csv_path.exists():
raise FileNotFoundError(f"Data file not found: {csv_path}")
df = pd.read_csv(csv_path)
if config.timestamp_column not in df.columns:
raise DataValidationError(
f"Timestamp column '{config.timestamp_column}' missing from dataset"
)
df[config.timestamp_column] = pd.to_datetime(
df[config.timestamp_column], errors="coerce"
)
df = df.dropna(subset=[config.timestamp_column])
df = df.sort_values(config.timestamp_column).reset_index(drop=True)
if config.timezone:
df[config.timestamp_column] = df[config.timestamp_column].dt.tz_localize(
"UTC"
).dt.tz_convert(config.timezone)
selected_features: Sequence[str]
if config.feature_columns:
missing = set(config.feature_columns) - set(df.columns)
if missing:
raise DataValidationError(
"Missing feature columns: " + ", ".join(sorted(missing))
)
selected_features = list(config.feature_columns)
else:
selected_features = _normalize_columns(
df.select_dtypes(include=["number"]).columns
)
selected_features = [
col
for col in selected_features
if col not in (config.timestamp_column, *config.id_columns)
]
if not selected_features:
raise DataValidationError(
"No numeric feature columns detected; specify them explicitly"
)
columns_to_keep = [config.timestamp_column, *config.id_columns, *selected_features]
df = df[columns_to_keep]
if config.dropna:
df = df.dropna(axis=0, how="any", subset=selected_features)
df = df.reset_index(drop=True)
df.attrs["feature_columns"] = selected_features
return df

View File

@@ -0,0 +1,167 @@
"""Score new historian data with a previously trained anomaly detector."""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Sequence
import joblib
import numpy as np
import pandas as pd
from data_loader import DataLoadConfig, load_timeseries
from feature_engineering import build_feature_matrix
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Run anomaly detection on new data using a saved model."
)
parser.add_argument("--data", required=True, help="Path to the CSV file to score.")
parser.add_argument(
"--model",
required=True,
help="Path to the joblib artifact generated by train.py.",
)
parser.add_argument(
"--timestamp-column",
help="Timestamp column name. Defaults to the value stored in the model artifact.",
)
parser.add_argument(
"--features",
nargs="*",
help="Optional override for base feature columns. Defaults to the model's training configuration.",
)
parser.add_argument(
"--id-columns",
nargs="*",
help="Optional override for identifier columns to retain in outputs.",
)
parser.add_argument(
"--output",
required=True,
help="Where to write the scored CSV (timestamp, ids, anomaly_score, is_anomaly, rank).",
)
parser.add_argument(
"--keep-features",
action="store_true",
help="Include engineered feature columns in the output file for deeper analysis.",
)
parser.add_argument(
"--alert-threshold",
type=float,
help="Optional manual threshold on the anomaly score. If set, flag rows with score < threshold.",
)
parser.add_argument(
"--top-n",
type=int,
default=None,
help="Optional count of the most anomalous rows to print to stdout for quick review.",
)
return parser.parse_args()
def prepare_feature_frame(
df: pd.DataFrame,
timestamp_column: str,
base_features: Sequence[str],
id_columns: Sequence[str],
artifact_config: dict,
):
feature_df, feature_columns = build_feature_matrix(
df,
timestamp_column=timestamp_column,
base_feature_columns=base_features,
include_rolling=artifact_config.get("include_rolling", True),
include_rate=artifact_config.get("include_rate", True),
rolling_windows=artifact_config.get("rolling_windows", ["5T", "15T", "60T"]),
id_columns=id_columns,
)
return feature_df, feature_columns
def main() -> None:
args = parse_args()
artifact = joblib.load(Path(args.model))
pipeline = artifact["pipeline"]
artifact_features = artifact["feature_columns"]
timestamp_column = args.timestamp_column or artifact.get("timestamp_column")
if not timestamp_column:
raise RuntimeError("Timestamp column must be provided via --timestamp-column or stored in the artifact.")
id_columns = list(
args.id_columns if args.id_columns is not None else artifact.get("id_columns", [])
)
base_features = list(
args.features if args.features is not None else artifact.get("base_features", [])
)
config = DataLoadConfig(
timestamp_column=timestamp_column,
feature_columns=base_features if base_features else None,
id_columns=id_columns,
)
raw_df = load_timeseries(Path(args.data), config)
if not base_features:
base_features = list(raw_df.attrs.get("feature_columns", []))
if not base_features:
raise RuntimeError(
"Unable to infer base feature columns. Provide them via --features."
)
feature_df, feature_columns = prepare_feature_frame(
raw_df,
timestamp_column=timestamp_column,
base_features=base_features,
id_columns=id_columns,
artifact_config=artifact.get("config", {}),
)
missing = set(artifact_features) - set(feature_columns)
if missing:
raise RuntimeError(
"Engineered features required by the model are missing: "
+ ", ".join(sorted(missing))
)
matrix = feature_df[artifact_features]
scores = pipeline.decision_function(matrix)
predictions = pipeline.predict(matrix) == -1
if args.alert_threshold is not None:
is_anomaly = scores < args.alert_threshold
else:
is_anomaly = predictions
rank = pd.Series(scores).rank(method="first", ascending=True).astype(int)
if args.keep_features:
context_cols = list(feature_df.columns)
else:
context_cols = [timestamp_column, *id_columns]
output_df = feature_df[context_cols].copy()
output_df["anomaly_score"] = scores
output_df["is_anomaly"] = is_anomaly
output_df["anomaly_rank"] = rank.values
output_path = Path(args.output)
output_path.parent.mkdir(parents=True, exist_ok=True)
output_df.to_csv(output_path, index=False)
total_anomalies = int(output_df["is_anomaly"].sum())
print(f"Wrote {len(output_df)} scored rows to {output_path}")
print(f"Flagged {total_anomalies} anomalies")
if args.top_n:
top_rows = output_df.nsmallest(args.top_n, "anomaly_score")
print("Top anomalous rows:")
print(top_rows[[timestamp_column, *id_columns, "anomaly_score", "is_anomaly"]])
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,124 @@
"""Domain-specific feature engineering helpers.
These routines create additional signals such as rolling averages,
standard deviations, and gradients that often improve anomaly detection
performance on process data.
"""
from __future__ import annotations
from typing import Iterable, List, Sequence, Tuple
import numpy as np
import pandas as pd
from pandas.api import types as pdt
def _ensure_sorted(df: pd.DataFrame, timestamp_column: str) -> pd.DataFrame:
if not df[timestamp_column].is_monotonic_increasing:
return df.sort_values(timestamp_column).reset_index(drop=True)
return df
def add_rolling_statistics(
df: pd.DataFrame,
feature_columns: Sequence[str],
timestamp_column: str,
windows: Iterable[str] = ("5T", "15T", "60T"),
min_periods: int = 3,
) -> pd.DataFrame:
"""Append rolling mean and std for each feature.
Parameters
----------
df:
DataFrame containing the source data.
feature_columns:
Columns to summarize with rolling statistics.
timestamp_column:
Name of the timestamp column (must be datetime-like).
windows:
Pandas offset aliases representing rolling windows (default minutes).
min_periods:
Minimum data points required within each window.
"""
df = df.copy()
df = _ensure_sorted(df, timestamp_column)
if not pdt.is_datetime64_any_dtype(df[timestamp_column]):
raise TypeError("timestamp_column must be datetime-like")
df = df.set_index(timestamp_column)
for window in windows:
rolling_obj = df[feature_columns].rolling(window=window, min_periods=min_periods)
mean_df = rolling_obj.mean().add_suffix(f"__rolling_mean_{window}")
std_df = rolling_obj.std(ddof=0).add_suffix(f"__rolling_std_{window}")
df = pd.concat([df, mean_df, std_df], axis=1)
df = df.reset_index()
return df
def add_rate_of_change(
df: pd.DataFrame,
feature_columns: Sequence[str],
timestamp_column: str,
) -> pd.DataFrame:
"""Append the first derivative (per-minute change) for each feature."""
df = df.copy()
df = _ensure_sorted(df, timestamp_column)
df = df.set_index(timestamp_column)
deltas = df.index.to_series().diff().dt.total_seconds().fillna(0)
seconds = deltas.to_numpy()
seconds[seconds == 0] = np.nan # Avoid division by zero
for col in feature_columns:
rate_col = f"{col}__rate_per_min"
df[rate_col] = df[col].diff() / seconds * 60.0
df[rate_col] = df[rate_col].fillna(0.0)
df = df.reset_index()
return df
def build_feature_matrix(
df: pd.DataFrame,
timestamp_column: str,
base_feature_columns: Sequence[str],
include_rolling: bool = True,
include_rate: bool = True,
rolling_windows: Iterable[str] = ("5T", "15T", "60T"),
id_columns: Sequence[str] | None = None,
) -> Tuple[pd.DataFrame, List[str]]:
"""Produce an enriched feature matrix for model consumption."""
id_columns = list(id_columns or [])
enriched = df.copy()
if include_rolling:
enriched = add_rolling_statistics(
enriched,
feature_columns=base_feature_columns,
timestamp_column=timestamp_column,
windows=rolling_windows,
)
if include_rate:
enriched = add_rate_of_change(
enriched,
feature_columns=base_feature_columns,
timestamp_column=timestamp_column,
)
feature_columns = [
col
for col in enriched.columns
if col not in {timestamp_column, *id_columns} and pdt.is_numeric_dtype(enriched[col])
]
columns_to_return = [timestamp_column, *id_columns, *feature_columns]
return enriched[columns_to_return], feature_columns

View File

@@ -0,0 +1,217 @@
"""Command-line entry point for training an anomaly detection model.
Example usage (PowerShell):
python ml/anomaly_detection/src/train.py ^
--data data/clean/process_snapshot.csv ^
--timestamp-column timestamp ^
--features steam_tph turbine_rpm conveyor_tph ^
--model-out ml/anomaly_detection/models/isolation_forest.joblib
"""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Sequence
import joblib
import pandas as pd
from sklearn.ensemble import IsolationForest
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from data_loader import DataLoadConfig, load_timeseries
from feature_engineering import build_feature_matrix
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Train an Isolation Forest on historian data to detect anomalies."
)
parser.add_argument(
"--data",
required=True,
help="Path to the CSV file containing historical measurements.",
)
parser.add_argument(
"--timestamp-column",
required=True,
help="Name of the timestamp column in the dataset.",
)
parser.add_argument(
"--features",
nargs="*",
default=None,
help="Optional explicit list of feature columns to use. Defaults to all numeric columns.",
)
parser.add_argument(
"--id-columns",
nargs="*",
default=(),
help="Columns that should be preserved in outputs but excluded from modelling.",
)
parser.add_argument(
"--contamination",
type=float,
default=0.02,
help="Expected fraction of anomalies in the dataset (Isolation Forest parameter).",
)
parser.add_argument(
"--n-estimators",
type=int,
default=200,
help="Number of trees for the Isolation Forest.",
)
parser.add_argument(
"--random-state",
type=int,
default=42,
help="Random seed for reproducibility.",
)
parser.add_argument(
"--model-out",
type=str,
default="ml/anomaly_detection/models/isolation_forest.joblib",
help="Where to save the fitted model pipeline.",
)
parser.add_argument(
"--scores-out",
type=str,
default="ml/anomaly_detection/outputs/training_scores.csv",
help="Optional path to write anomaly scores for the training data.",
)
parser.add_argument(
"--no-rolling",
action="store_true",
help="Disable rolling-window feature augmentation.",
)
parser.add_argument(
"--no-rate",
action="store_true",
help="Disable rate-of-change feature augmentation.",
)
parser.add_argument(
"--rolling-windows",
nargs="*",
default=["5T", "15T", "60T"],
help="Rolling window sizes (pandas offset aliases) for derived features.",
)
return parser.parse_args()
def ensure_parent_dir(path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
def fit_pipeline(feature_matrix: pd.DataFrame, feature_columns: Sequence[str], args: argparse.Namespace) -> Pipeline:
scaler = StandardScaler()
model = IsolationForest(
contamination=args.contamination,
n_estimators=args.n_estimators,
random_state=args.random_state,
n_jobs=-1,
)
pipeline = Pipeline([("scaler", scaler), ("model", model)])
pipeline.fit(feature_matrix[feature_columns])
return pipeline
def generate_scores(
pipeline: Pipeline,
feature_matrix: pd.DataFrame,
feature_columns: Sequence[str],
) -> pd.DataFrame:
transformed = feature_matrix[feature_columns]
decision_scores = pipeline.decision_function(transformed)
predictions = pipeline.predict(transformed) # 1 for normal, -1 for anomaly
scores_df = feature_matrix[[col for col in feature_matrix.columns if col not in feature_columns]].copy()
scores_df["anomaly_score"] = decision_scores
scores_df["is_anomaly"] = predictions == -1
scores_df["anomaly_rank"] = (
pd.Series(decision_scores).rank(method="first", ascending=True).astype(int).values
)
return scores_df
def main() -> None:
args = parse_args()
config = DataLoadConfig(
timestamp_column=args.timestamp_column,
feature_columns=args.features,
id_columns=args.id_columns,
)
raw_df = load_timeseries(Path(args.data), config)
if config.feature_columns:
base_features = list(config.feature_columns)
else:
base_features = list(raw_df.attrs.get("feature_columns", []))
if not base_features:
non_feature_columns = {args.timestamp_column, *config.id_columns}
base_features = [
col
for col in raw_df.columns
if col not in non_feature_columns and pd.api.types.is_numeric_dtype(raw_df[col])
]
if not base_features:
raise RuntimeError(
"Unable to determine feature columns. Specify them explicitly via --features."
)
feature_df, feature_columns = build_feature_matrix(
raw_df,
timestamp_column=args.timestamp_column,
base_feature_columns=base_features,
include_rolling=not args.no_rolling,
include_rate=not args.no_rate,
rolling_windows=args.rolling_windows,
id_columns=config.id_columns,
)
if not feature_columns:
raise RuntimeError("No feature columns available after feature engineering.")
pipeline = fit_pipeline(feature_df, feature_columns, args)
artifact = {
"pipeline": pipeline,
"feature_columns": list(feature_columns),
"timestamp_column": args.timestamp_column,
"id_columns": list(config.id_columns),
"base_features": list(base_features),
"config": {
"contamination": args.contamination,
"n_estimators": args.n_estimators,
"random_state": args.random_state,
"rolling_windows": args.rolling_windows,
"include_rolling": not args.no_rolling,
"include_rate": not args.no_rate,
},
}
model_path = Path(args.model_out)
ensure_parent_dir(model_path)
joblib.dump(artifact, model_path)
scores_df = generate_scores(pipeline, feature_df, feature_columns)
scores_path = Path(args.scores_out)
ensure_parent_dir(scores_path)
scores_df.to_csv(scores_path, index=False)
print(f"Model saved to {model_path}")
print(f"Training scores written to {scores_path}")
print(
f"Detected {(scores_df['is_anomaly'].sum())} anomalies out of {len(scores_df)} records"
)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,69 @@
# Database Agent Toolkit
This folder hosts utilities and documentation for the natural-language SQL agent.
## Folders
- `extractor/`: Python tooling to pull schema metadata from the MSSQL sandbox.
- `prompting/`: Prompt builders that merge curated context into LLM requests.
- `context/`: Generated artifacts (schema JSON, glossary, examples) injected into LLM prompts.
- `deployment/`: Docker Compose for hosting open-source SQL models via TGI.
- `sql_executor.py`: Validation + execution helpers for running generated SQL safely.
- `log_utils.py`: JSONL logging utilities for question/SQL traces.
- `ui/`: FastAPI backend and static frontend for a simple web interface.
- `knowledge_prep.md`: Checklist for curating high-quality agent context.
## Python Setup
1. **Install dependencies** (create a venv if needed):
```powershell
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
pip install -r db_agent/requirements.txt
```
Ensure the Microsoft ODBC driver (17 or 18) is installed on the machine.
2. **Configure environment variables** (never commit credentials):
```powershell
. .\db_agent\scripts\Set-DbEnv.ps1 -Server "SUGARSCALE\SQLEXPRESS" -Database "SugarScale_Lasuca" -Username "SugarAI"
```
Dot-source the helper so the variables stay in your session. It prompts for the password (or accept `-Password (Read-Host -AsSecureString)`) and sets the `DB_*` values expected by `DbSettings`. Pass `-Driver`, `-Encrypt`, or `-TrustCertificate` to override defaults.
3. **Run the schema extraction job**:
```powershell
python -m db_agent.extractor --job schema --schema dbo --output db_agent/context/schema.json
```
- `--schema`: restricts the crawl to a specific SQL schema (omit to capture all).
- `--output`: where to write the structured schema document consumed by the agent.
4. **Review the output** under `db_agent/context/` and commit sanitized artifacts alongside code when appropriate.
## Running the SQL Agent
1. Ensure the TGI container in `deployment/docker-compose.yml` is running (default endpoint `http://192.168.0.30:8080`).
2. Execute a question against the model:
```powershell
python -m db_agent.run_agent "How many loads were completed yesterday?" --tables dbo.SugarLoadData
```
The script prints JSON with `sql` and `summary` fields.
3. Use `--execute` to run the validated SQL against MSSQL (enforced `TOP` limit via `--max-rows`, default `500`):
```powershell
python -m db_agent.run_agent "Top gross loads this week" --tables dbo.SugarLoadData --execute --max-rows 200
```
Preview rows (up to 5) and the sanitized SQL are echoed to stdout.
4. Interactions are logged to `db_agent/logs/query_log.jsonl` by default; override with `--log-path` or disable logging via `--no-log`.
5. To point at a different inference endpoint, edit `LlmConfig.base_url` in `db_agent/client.py` (the client posts to `<base_url>/generate`).
## Web UI
1. Install the web dependencies (already in `db_agent/requirements.txt`).
2. Start the FastAPI server:
```powershell
uvicorn db_agent.ui.backend.main:app --reload --host 0.0.0.0 --port 8000
```
3. Open `http://localhost:8000/` to access the UI. Submit questions, optionally run SQL, and view results/preview tables.
4. Environment variables for MSSQL access must be set in the shell before launching the server.
## Next Steps
- Add additional extractor jobs (lookup value snapshots, glossary builders) following the same pattern as `schema_snapshot.py`.
- Integrate the extractor into CI/CD or a scheduled task to keep the agent context fresh.
- Use `knowledge_prep.md` as a guide when enriching the context files with human-curated insights.
- Extend `db_agent/client.py` with SQL validation/execution layers and logging of user questions vs. generated queries.
- Consider adding automated SQL result validation (e.g., schema assertions) before surfacing answers to end users.

View File

@@ -0,0 +1,15 @@
"""Tools for building and running the SugarScale SQL agent."""
from .client import SqlAgentClient, default_client
from .prompting import AgentContext, build_prompt, load_context
from .sql_executor import execute_sql, sanitize_sql
__all__ = [
"SqlAgentClient",
"default_client",
"AgentContext",
"build_prompt",
"load_context",
"execute_sql",
"sanitize_sql",
]

View File

@@ -0,0 +1,367 @@
"""Client utilities for calling the local TGI-hosted SQL model."""
from __future__ import annotations
import json
import logging
import re
from dataclasses import dataclass
from typing import Any, Dict, Optional
import requests
from .prompting import AgentContext, build_prompt, load_context
logger = logging.getLogger(__name__)
@dataclass
class LlmConfig:
base_url: str = "http://192.168.0.30:8080"
model: str = "defog/sqlcoder-7b-2"
temperature: float = 0.1
max_new_tokens: Optional[int] = 512
class SqlAgentClient:
"""Wrapper that builds prompts and fetches SQL from the LLM service."""
_FORMAT_REMINDER = (
"Reminder: Respond with valid JSON exactly as {\"sql\": \"<single T-SQL SELECT statement>\", "
"\"summary\": \"<one sentence summary>\"}. The sql value must start with SELECT, contain only one "
"statement, use SQL Server syntax (e.g., LIKE instead of ILIKE, ORDER BY without NULLS LAST/FIRST), and "
"avoid fabricated literals or extra filters. Only add WHERE conditions or time windows that the user explicitly mentioned. If clarification is required, set sql to an empty string and explain why in summary."
)
def __init__(self, context: AgentContext, llm_config: Optional[LlmConfig] = None) -> None:
self.context = context
self.config = llm_config or LlmConfig()
def build_request_payload(
self,
question: str,
table_hints: Optional[list[str]] = None,
*,
format_hint: Optional[str] = None,
) -> Dict[str, Any]:
prompt = build_prompt(
question=question,
context=self.context,
table_hints=table_hints,
format_hint=format_hint,
)
parameters: Dict[str, Any] = {
"temperature": max(self.config.temperature, 1e-5),
"return_full_text": False,
}
if self.config.max_new_tokens is not None:
parameters["max_new_tokens"] = self.config.max_new_tokens
return {
"inputs": prompt,
"parameters": parameters,
}
def query(self, question: str, table_hints: Optional[list[str]] = None) -> Dict[str, Any]:
warnings: list[str] = []
question_allows_timeframe = self._question_mentions_timeframe(question)
parsed: Optional[Dict[str, Any]] = None
for attempt in range(2):
if attempt == 1:
format_hint = (
self._FORMAT_REMINDER
+ f' The user question is: "{question}". Do not add filters beyond what is explicitly stated.'
)
else:
format_hint = None
payload = self.build_request_payload(question, table_hints, format_hint=format_hint)
parsed = self._invoke_generate(payload)
sql_text = parsed.get("sql", "") if isinstance(parsed, dict) else ""
normalized_sql = self._normalize_sql(sql_text) if sql_text else ""
parsed["sql"] = normalized_sql
if normalized_sql and not question_allows_timeframe:
normalized_sql, stripped_temporal = self._strip_unrequested_temporal_filters(normalized_sql)
if stripped_temporal:
parsed["sql"] = normalized_sql
warnings.append("Postprocess: Removed unrequested date/time filters from SQL output.")
if normalized_sql:
normalized_sql, stripped_compat = self._replace_non_sqlserver_syntax(normalized_sql)
if stripped_compat:
parsed["sql"] = normalized_sql
warnings.append("Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).")
if normalized_sql and normalized_sql.lstrip().lower().startswith("select"):
if warnings:
parsed["llm_warning"] = "; ".join(warnings)
return parsed
warning_message = parsed.get("llm_warning")
if not warning_message:
warning_message = "Model response did not include a valid SELECT statement."
# Capture repeated addition of unrequested filters for auditing
sql_text = parsed.get("sql", "")
if sql_text:
lowered_sql = sql_text.lower()
if any(phrase in lowered_sql for phrase in ("last 24", "last24", "24 hour", "24-hour")):
warning_message = (
"Model added an unrequested time filter. Ensure future responses only add filters present in the question."
)
warnings.append(f"Attempt {attempt + 1}: {warning_message}")
if attempt == 0:
logger.info("Retrying LLM request with explicit formatting reminder.")
continue
# Second attempt also failed
warnings.append("Attempt 2: Second attempt also failed to produce a valid SELECT statement.")
parsed["llm_warning"] = "; ".join(warnings)
return parsed
# Should not reach here, but provide a safe fallback
if parsed:
parsed.setdefault("sql", "")
parsed.setdefault("summary", "")
parsed["llm_warning"] = "; ".join(warnings) if warnings else "LLM did not produce a usable response."
return parsed
return {
"sql": "",
"summary": "",
"llm_warning": "LLM did not produce a usable response.",
}
def _invoke_generate(self, payload: Dict[str, Any]) -> Dict[str, Any]:
headers = {"Content-Type": "application/json"}
response = requests.post(
f"{self.config.base_url}/generate",
headers=headers,
data=json.dumps(payload),
timeout=120,
)
response.raise_for_status()
try:
data = response.json()
except ValueError:
body = response.text.strip()
return self._fallback_response(
raw=body,
message="LLM HTTP response was not JSON; returning raw text.",
)
content = data.get("generated_text") if isinstance(data, dict) else None
if not content:
raw = response.text.strip()
return self._fallback_response(
raw=raw or str(data),
message="LLM response missing generated_text field; returning raw text.",
)
return self._parse_response(content)
@staticmethod
def _strip_code_fence(text: str) -> str:
stripped = text.strip()
if stripped.startswith("```") and stripped.endswith("```"):
without_ticks = stripped.strip("`")
parts = without_ticks.split("\n", 1)
if len(parts) == 2:
body = parts[1]
else:
body = parts[0]
return body.rsplit("```", 1)[0] if "```" in body else body
return stripped
def _parse_response(self, content: str) -> Dict[str, Any]:
"""Attempt to decode JSON, handling common formatting wrappers."""
raw = content.strip()
candidates = [raw]
candidates.append(self._strip_code_fence(raw))
# Extract substring between first and last braces if needed
start = raw.find("{")
end = raw.rfind("}")
if start != -1 and end != -1 and end > start:
candidates.append(raw[start : end + 1])
for candidate in candidates:
candidate = candidate.strip()
if not candidate:
continue
try:
return json.loads(candidate)
except json.JSONDecodeError:
continue
# Heuristic: parse patterns like "SQL query: ... Summary: ..."
lower = raw.lower()
if "sql query:" in lower:
sql_start = lower.find("sql query:") + len("sql query:")
summary_start = lower.find("summary:")
if summary_start != -1:
sql_text = raw[sql_start:summary_start].strip()
summary_text = raw[summary_start + len("summary:") :].strip()
return {"sql": sql_text, "summary": summary_text}
if lower.startswith("sql:"):
sql_text = raw.split(":", 1)[1].strip()
return {"sql": sql_text, "summary": ""}
# Handle outputs like "... Summary: ..." (with or without explicit SQL label)
summary_idx = lower.rfind("summary:")
if summary_idx != -1:
sql_section = raw[:summary_idx].strip()
summary_text = raw[summary_idx + len("summary:") :].strip()
# Remove wrapping quotes if present
if summary_text.startswith("\"") and summary_text.endswith("\""):
summary_text = summary_text[1:-1]
if sql_section.lower().startswith("sql generated:"):
sql_section = sql_section[len("sql generated:") :].strip()
return {"sql": sql_section, "summary": summary_text}
# Final fallback: treat entire content as SQL and leave summary blank.
if raw.upper().startswith("SELECT") or "SELECT" in raw.upper():
return {"sql": raw.strip(), "summary": ""}
return self._fallback_response(
raw=raw,
message="LLM output could not be parsed; returning raw text.",
)
@staticmethod
def _fallback_response(raw: str, message: str) -> Dict[str, Any]:
preview = raw[:200] if raw else "(empty response)"
logger.warning("%s preview=%s", message, preview)
return {
"sql": "",
"summary": raw,
"llm_warning": f"{message} Preview: {preview}",
}
@staticmethod
def _question_mentions_timeframe(question: str) -> bool:
lowered = question.lower()
if re.search(
r"\b(today|yesterday|tonight|this|current|previous|prior|recent|last|past|since|ago|between|before|after|during)\b",
lowered,
):
return True
if re.search(
r"\b(day|days|week|weeks|month|months|quarter|quarters|year|years|hour|hours|minute|minutes)\b",
lowered,
):
return True
if re.search(r"\b(january|february|march|april|may|june|july|august|september|october|november|december)\b", lowered):
return True
if re.search(r"\b(mon|tue|wed|thu|fri|sat|sun)(day)?\b", lowered):
return True
if re.search(r"\b20\d{2}\b", lowered):
return True
return False
@staticmethod
def _strip_unrequested_temporal_filters(sql: str) -> tuple[str, bool]:
candidate = sql
temporal_regex = r"(DATEADD|DATEDIFF|DATEPART|SYSDATETIME|GETDATE|CURRENT_TIMESTAMP)"
changed = False
clause_pattern = re.compile(
rf"\s+(AND|OR)\s+[^;]*?{temporal_regex}[^;]*?(?=(\bAND\b|\bOR\b|\bGROUP BY\b|\bORDER BY\b|\bHAVING\b|$))",
re.IGNORECASE | re.DOTALL,
)
candidate, replaced = clause_pattern.subn("", candidate)
if replaced:
changed = True
where_pattern = re.compile(
rf"\bWHERE\b\s+[^;]*?{temporal_regex}[^;]*?(?=(\bGROUP BY\b|\bORDER BY\b|\bHAVING\b|$))",
re.IGNORECASE | re.DOTALL,
)
candidate, replaced = where_pattern.subn("", candidate)
if replaced:
changed = True
dangling_where_pattern = re.compile(r"\bWHERE\b\s*(?=(GROUP BY|ORDER BY|HAVING|$))", re.IGNORECASE)
candidate, replaced = dangling_where_pattern.subn("", candidate)
if replaced:
changed = True
if changed:
candidate = re.sub(r"\s{2,}", " ", candidate)
candidate = re.sub(r"\s+(GROUP BY|ORDER BY|HAVING)\b", r" \1", candidate, flags=re.IGNORECASE)
candidate = re.sub(r"\s+;", ";", candidate)
return candidate.strip(), changed
@staticmethod
def _normalize_sql(sql_text: str) -> str:
text = sql_text.strip()
# Remove markdown fences if still present
if text.startswith("```") and text.endswith("```"):
inner = text.strip("`")
parts = inner.split("\n", 1)
text = parts[1] if len(parts) == 2 else parts[0]
text = text.rsplit("```", 1)[0]
prefix_pattern = re.compile(r"^[\s\.\?\-:\*•]*sql(?:\s+(?:query|statement))?\s*:\s*", re.IGNORECASE)
text = prefix_pattern.sub("", text, count=1)
alt_prefix_pattern = re.compile(r"^[\s\.\?\-:\*•]*(?:generated sql|query|answer)\s*:\s*", re.IGNORECASE)
text = alt_prefix_pattern.sub("", text, count=1)
# Drop leading punctuation or bullet artifacts before the SELECT keyword
lowered = text.lower()
select_idx = lowered.find("select")
if select_idx > 0:
leading = text[:select_idx]
if leading.strip(" \n\t\r:-*•?.") == "":
text = text[select_idx:]
# Remove any trailing summary section that may still be attached
summary_split = re.split(r"(?i)\bsummary\s*:", text, maxsplit=1)
if summary_split:
text = summary_split[0]
return text.strip()
@staticmethod
def _replace_non_sqlserver_syntax(sql_text: str) -> tuple[str, bool]:
changed = False
sql = sql_text
# Replace ILIKE with LIKE + UPPER for case-insensitive matching
def replace_ilike(match: re.Match[str]) -> str:
nonlocal changed
column = match.group("column")
value = match.group("value")
if column.startswith('"') and column.endswith('"'):
column = f"[{column[1:-1]}]"
if value.startswith('"') and value.endswith('"'):
value = f"'{value[1:-1]}'"
changed = True
return f"UPPER({column}) LIKE UPPER({value})"
ilike_pattern = re.compile(
r"(?P<column>(?:[\w\.\[\]]+|\"[^\"]+\"))\s+ILIKE\s+(?P<value>'[^']*'|\"[^\"]*\"|:[\w_]+)",
re.IGNORECASE,
)
sql = ilike_pattern.sub(replace_ilike, sql)
# Remove NULLS FIRST/LAST clauses
nulls_pattern = re.compile(r"\s+NULLS\s+(?:FIRST|LAST)", re.IGNORECASE)
if nulls_pattern.search(sql):
sql = nulls_pattern.sub("", sql)
changed = True
return sql.strip(), changed
def default_client() -> SqlAgentClient:
context = load_context()
config = LlmConfig()
return SqlAgentClient(context=context, llm_config=config)

View File

@@ -0,0 +1,27 @@
[
{
"question": "How many loads were completed yesterday?",
"sql": "SELECT COUNT(*) AS load_count\nFROM dbo.SugarLoadData\nWHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);",
"notes": "Uses DateOut to ensure the truck exited; bounds the window on the local date."
},
{
"question": "Show the top 5 heaviest loads in the past week.",
"sql": "SELECT TOP (5) SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\nFROM dbo.SugarLoadData\nWHERE DateOut >= DATEADD(day, -7, SYSDATETIME())\nORDER BY GrossWt DESC;",
"notes": "Ranks by gross weight; includes net/tare columns for context."
},
{
"question": "List average payload tons per hauling company for the last 30 days.",
"sql": "SELECT TCompanyName, AVG(Tons) AS avg_tons, COUNT(*) AS load_count\nFROM dbo.SugarLoadData\nWHERE DateOut >= DATEADD(day, -30, SYSDATETIME())\n AND Tons IS NOT NULL\nGROUP BY TCompanyName\nORDER BY avg_tons DESC;",
"notes": "Filters out null payloads and groups by company for business comparison."
},
{
"question": "Which vehicles have missing tare weights on recent loads?",
"sql": "SELECT VehicleId_Fk, COUNT(*) AS missing_tare_count\nFROM dbo.SugarLoadData\nWHERE DateOut >= DATEADD(day, -14, SYSDATETIME())\n AND (TareWt IS NULL OR TareWt = 0)\nGROUP BY VehicleId_Fk\nORDER BY missing_tare_count DESC;",
"notes": "Helps operations schedule tare recalibration."
},
{
"question": "Provide hourly load counts for the current day.",
"sql": "SELECT DATEPART(hour, DateOut) AS hour_of_day, COUNT(*) AS loads\nFROM dbo.SugarLoadData\nWHERE DateOut >= CAST(SYSDATETIME() AS date)\nGROUP BY DATEPART(hour, DateOut)\nORDER BY hour_of_day;",
"notes": "Generates time-series data for real-time dashboards; assumes DateOut in local timezone."
}
]

View File

@@ -0,0 +1,44 @@
# SugarScale MSSQL Glossary
Use this glossary to translate operator language into database columns for the SQL agent.
## Core Tables
- **dbo.SugarLoadData**: Per-load grain deliveries recorded at the truck scale. Each row represents a truck entering/exiting the facility with weight measurements and logistics metadata.
- **dbo.SugarVehicles**: Reference table for registered trucks/trailers and their default properties (company, RFID tag, tare weight).
- **dbo.SugarParams**: System parameters; currently stores a single `StartTime` indicating when the scale captured data begins.
## Common Terms
- **Load** → `dbo.SugarLoadData`
- `SugarLoadID_Pk`: Unique identifier for a scale transaction (primary key).
- `VehicleId_Fk`: Truck or vehicle identifier referencing `dbo.SugarVehicles.VehicleId_Pk`.
- `TrailerTypeID`: Trailer classification (e.g., hopper, dump). Stored as free text; standardize before analytics when possible.
- `TCompanyName`: Hauling company name as captured at the kiosk.
- `DriverID`: Driver badge or license; alphanumeric string up to 500 chars.
- `LoadingLocation`: Where the load originated (hopper, wh1, wh2, etc.).
- `Destination`: Planned delivery point or storage yard.
- `DateIn`: Timestamp when the vehicle weighed in (in local plant timezone).
- `DateOut`: Timestamp when the vehicle weighed out or exited.
- `ScaleWT`: Raw indicator from the scale prior to adjustments (integer pounds).
- `GrossWt`: Gross weight measured on exit, in pounds.
- `TareIN`: Tare weight observed on entry (empty truck), in pounds.
- `TareWt`: Tare weight applied for net calculations; may be sourced from default or reweigh.
- `Tons`: Net payload in short tons (calculated from gross-tare).
- `LoadType`: Category flag (e.g., sugar, molasses). Align with scheduling terminology.
- `Alt_Barcode_Scan`: Secondary barcode capture used for redundancy; 50-character limit.
- **Vehicle** → `dbo.SugarVehicles`
- `VehicleId_Pk`: Unique truck identifier (matches `VehicleId_Fk`).
- `TCompanyName`: Default operator/contractor name for the vehicle record.
- `RFID`: RFID tag assigned to the truck for automatic gate reads.
- `Tare`: Stored tare weight (decimal, pounds). Use when `SugarLoadData.TareWt` is null.
- `LastTareTime`: Timestamp of the last verified tare measurement.
- `DefaultDest`: Common destination code used to prefill load forms.
- **System Start** → `dbo.SugarParams.StartTime`
- Indicates the earliest reliable timestamp in the SugarLoadData feed; use when bounding historical reports.
## Business Notes
- Weight fields are stored in pounds except `Tons`, which is short tons (`lbs / 2000`). Convert before aggregating if downstream systems expect metric tons.
- `DateIn` and `DateOut` are expected to be in local plant time without timezone metadata; adjust to UTC when integrating with other systems.
- Null `VehicleId_Fk` rows usually indicate walk-on loads or manual overrides; treat carefully when joining to `SugarVehicles`.
- `LoadType` and `TrailerTypeID` are free text and may have inconsistent casing; normalize to upper case when filtering.

View File

@@ -0,0 +1,186 @@
{
"tables": {
"dbo.SugarLoadData": {
"columns": [
{
"default": null,
"max_length": 255,
"name": "SugarLoadID_Pk",
"nullable": false,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "VehicleId_Fk",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "TrailerTypeID",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "TCompanyName",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 500,
"name": "DriverID",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "LoadingLocation",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "Destination",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": null,
"name": "DateIn",
"nullable": true,
"type": "datetime"
},
{
"default": null,
"max_length": null,
"name": "DateOut",
"nullable": true,
"type": "datetime"
},
{
"default": null,
"max_length": null,
"name": "ScaleWT",
"nullable": true,
"type": "int"
},
{
"default": null,
"max_length": null,
"name": "GrossWt",
"nullable": true,
"type": "float"
},
{
"default": null,
"max_length": null,
"name": "TareIN",
"nullable": true,
"type": "float"
},
{
"default": null,
"max_length": null,
"name": "TareWt",
"nullable": true,
"type": "float"
},
{
"default": null,
"max_length": null,
"name": "Tons",
"nullable": true,
"type": "float"
},
{
"default": null,
"max_length": 255,
"name": "LoadType",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 50,
"name": "Alt_Barcode_Scan",
"nullable": true,
"type": "nvarchar"
}
],
"name": "SugarLoadData",
"relationships": [],
"schema": "dbo"
},
"dbo.SugarParams": {
"columns": [
{
"default": null,
"max_length": null,
"name": "StartTime",
"nullable": false,
"type": "datetime"
}
],
"name": "SugarParams",
"relationships": [],
"schema": "dbo"
},
"dbo.SugarVehicles": {
"columns": [
{
"default": null,
"max_length": 255,
"name": "VehicleId_Pk",
"nullable": false,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "TCompanyName",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 150,
"name": "RFID",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": null,
"name": "Tare",
"nullable": true,
"type": "decimal"
},
{
"default": null,
"max_length": null,
"name": "LastTareTime",
"nullable": true,
"type": "datetime"
},
{
"default": null,
"max_length": 50,
"name": "DefaultDest",
"nullable": true,
"type": "nvarchar"
}
],
"name": "SugarVehicles",
"relationships": [],
"schema": "dbo"
}
}
}

View File

@@ -0,0 +1,76 @@
# Enum hints and typical ranges sourced from the SugarScale MSSQL sandbox.
# Update these after running profiling queries to keep the agent grounded.
columns:
dbo.SugarLoadData.LoadType:
values:
- Sugar
- Molases
notes: "Free-text field; normalize casing before comparisons."
dbo.SugarLoadData.TrailerTypeID:
values:
- Dump
notes: "Derived from manual entry; expect misspellings such as 'hopper' or 'Dump Trailer'."
dbo.SugarLoadData.LoadingLocation:
values:
- Hopper
- WH1
- WH2
- WH3
- BB
notes: "Locations map to historian area tags; keep a lookup table in sync with operations."
dbo.SugarLoadData.Destination:
values:
- Baldwin 3
- CSC
- BB
- Railcar
- LSR
- WH1
- WH2
- Barge
- Caldwell
- Other
notes: "Destination names align with production reporting dashboards; treat nulls as 'Unassigned'."
dbo.SugarLoadData.TCompanyName:
values:
- AOA
- JJAG,LLC
- Michael Durand
- Atchafalaya Seafood
- CSC
- Southern Prestige ENT
- LACA
- RALPH CALLIER
- ASR
- 14-1
- BIGDAWG
- Lasuca
- Earl Pania
- J Bradley
notes: "Company names align with production reporting dashboards; treat nulls as 'Unassigned'."
ranges:
dbo.SugarLoadData.GrossWt:
units: pounds
typical_min: 20000
typical_max: 88000
notes: "Scale enforces 40-ton cap; values above 90000 suggest sensor error."
dbo.SugarLoadData.TareWt:
units: pounds
typical_min: 14000
typical_max: 45000
notes: "Use stored vehicle tare when this column is null; sudden drops >20% flag for review."
dbo.SugarLoadData.Tons:
units: short_tons
typical_min: 5
typical_max: 40
notes: "Calculated payload; negative values indicate data entry mistakes."
confidence_flags:
dbo.SugarLoadData.VehicleId_Fk:
null_meaning: "Manual override or unregistered vehicle"
mitigation: "Join to SugarVehicles only after filtering nulls or alias to 'UNKNOWN_VEHICLE'."
dbo.SugarLoadData.DateOut:
null_meaning: "Truck has not exited; treat as active load."
mitigation: "Filter out null DateOut when reporting completed deliveries."

View File

@@ -0,0 +1,33 @@
# Local TGI Deployment for SQLCoder
This docker compose file runs Hugging Face Text Generation Inference (TGI) serving the `defog/sqlcoder-7b-2` model.
## Prerequisites
- NVIDIA GPU with recent drivers and CUDA runtime that matches the `nvidia-container-toolkit` installation.
- Docker and `docker compose` v2.
- Hugging Face access token with model download permissions (`HUGGING_FACE_HUB_TOKEN`).
## Usage
1. Export your Hugging Face token in the shell where you run compose:
```powershell
$env:HUGGING_FACE_HUB_TOKEN = "hf_..."
```
2. Launch the stack:
```powershell
docker compose -f db_agent/deployment/docker-compose.yml up -d
```
3. Check logs:
```powershell
docker compose -f db_agent/deployment/docker-compose.yml logs -f
```
4. The TGI OpenAI-compatible endpoint will be available at `http://localhost:8080/v1`. Use it with `openai`-compatible SDKs or direct HTTP calls.
## Notes
- The compose file pins `CUDA_VISIBLE_DEVICES=2` to target the 24 GB RTX 3090; update if your GPU indices differ.
- Token limits are tightened (`--max-total-tokens=3072`, `--max-input-length=2048`) to stay within 1624 GB cards.
- Models are cached on the `model-cache` volume to avoid re-downloading.
- To shut down:
```powershell
docker compose -f db_agent/deployment/docker-compose.yml down
```
- For CPU-only testing, remove the `deploy.resources` block and expect very slow inference.

View File

@@ -0,0 +1,36 @@
version: "3.9"
services:
sqlcoder-tgi:
image: ghcr.io/huggingface/text-generation-inference:2.1.0
container_name: sqlcoder-tgi
restart: unless-stopped
ports:
- "8080:80"
environment:
# Set your Hugging Face token to pull gated models
HUGGING_FACE_HUB_TOKEN: ${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}
# Pin to the 3090 (adjust if your GPU order differs)
CUDA_VISIBLE_DEVICES: "0"
DISABLE_FLASH_ATTENTION: "1"
CUDA_LAUNCH_BLOCKING: "1"
command:
- "--model-id=defog/sqlcoder-7b-2"
- "--dtype=float16"
- "--max-total-tokens=6144"
- "--max-input-length=4096"
- "--max-batch-prefill-tokens=4560"
- "--cuda-memory-fraction=0.9"
- "--trust-remote-code"
volumes:
- model-cache:/data
deploy:
resources:
reservations:
devices:
- capabilities: [gpu]
count: 1
driver: nvidia
volumes:
model-cache:

View File

@@ -0,0 +1 @@
"""Utilities for extracting database context artifacts for the SQL agent."""

View File

@@ -0,0 +1,5 @@
from .cli import main
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,46 @@
"""Command-line interface for database context extraction jobs."""
from __future__ import annotations
import argparse
from pathlib import Path
from . import schema_snapshot
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Extract schema and contextual artifacts for the SQL agent.",
)
parser.add_argument(
"--schema",
default=None,
help="Optional SQL Server schema to filter on (defaults to all schemas).",
)
parser.add_argument(
"--output",
default="db_agent/context/schema.json",
help="Path to write the schema JSON document.",
)
parser.add_argument(
"--job",
choices=["schema"],
default="schema",
help="Extraction job to run (currently only 'schema').",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
output_path = Path(args.output)
if args.job == "schema":
result = schema_snapshot.run(schema=args.schema, output=output_path)
print(f"Schema document written to {result}")
else:
raise RuntimeError(f"Unsupported job: {args.job}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,175 @@
"""Extract schema metadata from the SugarScale MSSQL database."""
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List
import sqlalchemy as sa
from sqlalchemy.engine import Engine
from .settings import DbSettings
@dataclass
class TableColumn:
table_schema: str
table_name: str
column_name: str
data_type: str
is_nullable: bool
column_default: str | None
character_maximum_length: int | None
@dataclass
class ForeignKeyRelation:
source_schema: str
source_table: str
source_column: str
target_schema: str
target_table: str
target_column: str
def create_engine(settings: DbSettings) -> Engine:
connection_uri = (
"mssql+pyodbc:///?odbc_connect=" + sa.engine.url.quote_plus(settings.connection_string())
)
return sa.create_engine(connection_uri, fast_executemany=True)
def fetch_columns(engine: Engine, schema: str | None = None) -> List[TableColumn]:
columns: List[TableColumn] = []
query = sa.text(
"""
SELECT
TABLE_SCHEMA,
TABLE_NAME,
COLUMN_NAME,
DATA_TYPE,
IS_NULLABLE,
COLUMN_DEFAULT,
CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (:schema IS NULL OR TABLE_SCHEMA = :schema)
ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION
"""
)
with engine.connect() as conn:
result = conn.execute(query, {"schema": schema})
for row in result:
columns.append(
TableColumn(
table_schema=row.TABLE_SCHEMA,
table_name=row.TABLE_NAME,
column_name=row.COLUMN_NAME,
data_type=row.DATA_TYPE,
is_nullable=(row.IS_NULLABLE == "YES"),
column_default=row.COLUMN_DEFAULT,
character_maximum_length=row.CHARACTER_MAXIMUM_LENGTH,
)
)
return columns
def fetch_foreign_keys(engine: Engine, schema: str | None = None) -> List[ForeignKeyRelation]:
relations: List[ForeignKeyRelation] = []
query = sa.text(
"""
SELECT
fk_tab.name AS source_table,
fk_col.name AS source_column,
fk_sch.name AS source_schema,
pk_tab.name AS target_table,
pk_col.name AS target_column,
pk_sch.name AS target_schema
FROM sys.foreign_key_columns fkc
INNER JOIN sys.tables fk_tab ON fkc.parent_object_id = fk_tab.object_id
INNER JOIN sys.schemas fk_sch ON fk_tab.schema_id = fk_sch.schema_id
INNER JOIN sys.columns fk_col ON fkc.parent_object_id = fk_col.object_id AND fkc.parent_column_id = fk_col.column_id
INNER JOIN sys.tables pk_tab ON fkc.referenced_object_id = pk_tab.object_id
INNER JOIN sys.schemas pk_sch ON pk_tab.schema_id = pk_sch.schema_id
INNER JOIN sys.columns pk_col ON fkc.referenced_object_id = pk_col.object_id AND fkc.referenced_column_id = pk_col.column_id
WHERE (:schema IS NULL OR fk_sch.name = :schema)
ORDER BY fk_sch.name, fk_tab.name
"""
)
with engine.connect() as conn:
result = conn.execute(query, {"schema": schema})
for row in result:
relations.append(
ForeignKeyRelation(
source_schema=row.source_schema,
source_table=row.source_table,
source_column=row.source_column,
target_schema=row.target_schema,
target_table=row.target_table,
target_column=row.target_column,
)
)
return relations
def assemble_schema_document(columns: Iterable[TableColumn], relations: Iterable[ForeignKeyRelation]) -> Dict[str, Any]:
schema_doc: Dict[str, Any] = {"tables": {}}
for col in columns:
table_key = f"{col.table_schema}.{col.table_name}"
table_entry = schema_doc["tables"].setdefault(
table_key,
{
"schema": col.table_schema,
"name": col.table_name,
"columns": [],
"relationships": [],
},
)
table_entry["columns"].append(
{
"name": col.column_name,
"type": col.data_type,
"nullable": col.is_nullable,
"default": col.column_default,
"max_length": col.character_maximum_length,
}
)
for rel in relations:
table_key = f"{rel.source_schema}.{rel.source_table}"
table_entry = schema_doc["tables"].setdefault(
table_key,
{
"schema": rel.source_schema,
"name": rel.source_table,
"columns": [],
"relationships": [],
},
)
table_entry["relationships"].append(
{
"target": f"{rel.target_schema}.{rel.target_table}",
"source_column": rel.source_column,
"target_column": rel.target_column,
}
)
return schema_doc
def write_schema_json(output_path: Path, schema_doc: Dict[str, Any]) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("w", encoding="utf-8") as f:
json.dump(schema_doc, f, indent=2, sort_keys=True)
def run(schema: str | None = None, output: Path | None = None) -> Path:
settings = DbSettings.from_env()
engine = create_engine(settings)
columns = fetch_columns(engine, schema=schema)
relations = fetch_foreign_keys(engine, schema=schema)
schema_doc = assemble_schema_document(columns, relations)
output_path = output or Path("db_agent/context/schema.json")
write_schema_json(output_path, schema_doc)
return output_path

View File

@@ -0,0 +1,81 @@
"""Configuration helpers for connecting to the MSSQL sandbox."""
from __future__ import annotations
import os
from dataclasses import dataclass
@dataclass(frozen=True)
class DbSettings:
"""Environment-driven connection settings for SQL Server.
Required variables:
- DB_SERVER (e.g.,
- DB_DATABASE (e.g., "SugarScale_Lasuca")
- DB_USERNAME (database login)
- DB_PASSWORD (database password)
Optional overrides:
- DB_DRIVER (defaults to "$env")
- DB_ENCRYPT ("true" to enable TLS)
- DB_TRUST_CERT ("true" to trust the server certificate)
"""
server: str
database: str
username: str
password: str
driver: str = "ODBC Driver 18 for SQL Server"
encrypt: bool = True
trust_server_certificate: bool = True
@classmethod
def from_env(cls) -> "DbSettings":
missing: list[str] = []
server = os.getenv("DB_SERVER")
if not server:
missing.append("DB_SERVER")
database = os.getenv("DB_DATABASE")
if not database:
missing.append("DB_DATABASE")
username = os.getenv("DB_USERNAME")
if not username:
missing.append("DB_USERNAME")
password = os.getenv("DB_PASSWORD")
if not password:
missing.append("DB_PASSWORD")
if missing:
raise RuntimeError(
"Missing required environment variables: " + ", ".join(missing)
)
driver = os.getenv("DB_DRIVER", "ODBC Driver 18 for SQL Server")
encrypt = os.getenv("DB_ENCRYPT", "true").lower() == "true"
trust = os.getenv("DB_TRUST_CERT", "true").lower() == "true"
return cls(
server=server,
database=database,
username=username,
password=password,
driver=driver,
encrypt=encrypt,
trust_server_certificate=trust,
)
def connection_string(self) -> str:
parts = [
f"DRIVER={{{self.driver}}}",
f"SERVER={self.server}",
f"DATABASE={self.database}",
f"UID={self.username}",
f"PWD={self.password}",
]
if self.encrypt:
parts.append("Encrypt=yes")
if self.trust_server_certificate:
parts.append("TrustServerCertificate=yes")
parts.append("MARS_Connection=yes")
return ";".join(parts)

View File

@@ -0,0 +1,67 @@
# Database Agent Knowledge Prep
Use this checklist when preparing context for the natural-language SQL agent targeting our MSSQL sandbox.
## 1. Schema Catalog
- Summarize each table: name, purpose, primary keys, row granularity.
- List columns with data types and short descriptions; call out nullable fields.
- Document relationships: foreign-key paths, cardinality, and join direction.
- Recommended format (YAML example):
```yaml
tables:
production_events:
description: "Aggregated production metrics per line and hour."
columns:
- name: event_id
type: INT IDENTITY PRIMARY KEY
description: "Unique row ID."
nullable: false
- name: line_id
type: INT
description: "Foreign key to lines.id."
nullable: false
relationships:
- target: lines.id
via: production_events.line_id
cardinality: many-to-one
```
## 2. Business Semantics
- Provide glossary entries translating operator language to schema terms (e.g., "downtime" = `status_code` IN ('STOP','IDLE')).
- Explain derived metrics (OEE, throughput, scrap rate) and point to source columns.
- Note standard filters such as default time windows or equipment subsets.
## 3. Constraints & Guardrails
- Specify the read-only SQL credential and allowed schemas.
- List restricted tables, PII fields, or aggregates-only policies.
- Define execution limits: use `TOP` N defaults, row caps, timeout expectations.
- Capture timezone rules (UTC vs. local), especially for reporting dates.
## 4. Column Value Hints
- Enumerate controlled vocabularies (status codes, shift codes, unit names).
- Record measurement units and typical ranges to guide threshold suggestions.
- Mention any sentinel values representing missing or error states.
## 5. Worked Examples
- Include natural-language question, approved SQL, and a quick rationale.
- Aim for 5-10 examples covering joins, filters, time windows, aggregations.
- Store as Markdown table or JSON array for programmatic retrieval:
```json
[
{
"question": "Show top 10 downtime events last week for line A.",
"sql": "SELECT TOP (10) event_id, start_time, duration_min FROM downtime_events WHERE line_id = 'A' AND start_time >= DATEADD(day, -7, SYSUTCDATETIME()) ORDER BY duration_min DESC;",
"notes": "Uses UTC timestamps, filters to line A, orders by duration."
}
]
```
## 6. Delivery Format
- Consolidate the above into a single Markdown or JSON document checked into `db_agent/context/`.
- Keep the file under 20 KB so it can be injected directly into prompts; otherwise plan a retrieval step.
- Version changes alongside schema migrations so the agent stays accurate.
## 7. Maintenance Tips
- Regenerate the schema summary whenever the database structure changes (use `INFORMATION_SCHEMA`).
- Review logs of model-generated SQL to discover recurring gaps in the context.
- Expand the glossary with real user questions and clarifications over time.

View File

@@ -0,0 +1,52 @@
"""Helpers for recording agent interactions to disk."""
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
DEFAULT_LOG_PATH = Path("db_agent/logs/query_log.jsonl")
def log_interaction(
*,
question: str,
generated_sql: str,
summary: str,
sanitized_sql: Optional[str] = None,
row_count: Optional[int] = None,
execution_status: Optional[str] = None,
execution_error: Optional[str] = None,
raw_response: Optional[str] = None,
user_feedback: Optional[str] = None,
log_path: Path | None = None,
metadata: Optional[dict[str, Any]] = None,
) -> Path:
"""Append a single interaction entry to a JSONL log."""
path = log_path or DEFAULT_LOG_PATH
path.parent.mkdir(parents=True, exist_ok=True)
entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"question": question,
"generated_sql": generated_sql,
"summary": summary,
"sanitized_sql": sanitized_sql,
"row_count": row_count,
"execution_status": execution_status,
"execution_error": execution_error,
"raw_response": raw_response,
"user_feedback": user_feedback,
}
if metadata:
entry["metadata"] = metadata
# Remove None values for cleaner logs
entry = {key: value for key, value in entry.items() if value is not None}
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(entry, ensure_ascii=False) + "\n")
return path

View File

@@ -0,0 +1,141 @@
{"timestamp": "2025-10-18T04:29:01.528021+00:00", "question": "How many loads were completed yesterday?", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"tables_hint": ["dbo.SugarLoadData"], "execution_requested": false}}
{"timestamp": "2025-10-18T04:35:54.612705+00:00", "question": "How many loads were completed yesterday?", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"tables_hint": ["dbo.SugarLoadData"], "execution_requested": true, "columns": ["load_count"], "preview_rows": 1}}
{"timestamp": "2025-10-18T04:44:22.465579+00:00", "question": "What was the heaviest load yesterday?", "generated_sql": "{\"sql\": SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);, \"summary\": \"The heaviest load yesterday was 88,000 pounds.\"}", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.SugarLoaddata"]}}
{"timestamp": "2025-10-18T04:45:35.777925+00:00", "question": "What was the heaviest load yesterday?", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoaddata"]}}
{"timestamp": "2025-10-18T04:47:25.880870+00:00", "question": "how many loads today", "generated_sql": "Answer: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:47:58.248895+00:00", "question": "how many loads today", "generated_sql": "Answer: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:51:27.201815+00:00", "question": "how many loads this week", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, 1, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:52:07.641419+00:00", "question": "how many loads this week", "generated_sql": "{\"sql\": SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:52:22.427721+00:00", "question": "how many loads this week", "generated_sql": "{\"sql\": SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:52:32.431951+00:00", "question": "how many loads this week", "generated_sql": "{\"sql\": SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:52:54.585002+00:00", "question": "how many loads today", "generated_sql": "Answer: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:53:24.359951+00:00", "question": "how many loads today", "generated_sql": "Answer: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:55:16.554311+00:00", "question": "how many loads today", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:55:24.064499+00:00", "question": "how many loads today", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:55:45.770169+00:00", "question": "how many loads this week", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, 1, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, 1, CAST(SYSDATETIME() AS date))", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:56:36.711324+00:00", "question": "how many loads this past monday", "generated_sql": "{\"sql\": SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -7, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date) AND EXTRACT(dow FROM DateOut) = 1;, \"summary\": \"There were 7 loads on Monday.\"}", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:57:48.978022+00:00", "question": "what was the heaviest load last week", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME());", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:58:24.756279+00:00", "question": "what was the heaviest load last week.", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME());", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:58:30.747532+00:00", "question": "what was the heaviest load last week.", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME());", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:58:36.367704+00:00", "question": "what was the heaviest load last week.", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date))", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T05:01:57.321230+00:00", "question": "loads", "generated_sql": "SELECT COUNT(*) AS total_loads FROM dbo.SugarLoadData;", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS total_loads FROM dbo.SugarLoadData", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": null}}
{"timestamp": "2025-10-18T05:02:08.225378+00:00", "question": "loads today", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": null}}
{"timestamp": "2025-10-18T05:02:56.822781+00:00", "question": "heaviest load last week", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date))", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": null}}
{"timestamp": "2025-10-18T05:13:13.202846+00:00", "question": "loads yesterday", "generated_sql": "that were not completed.\n SQL: SELECT COUNT(*) AS incomplete_loads FROM dbo.SugarLoadData WHERE DateOut IS NULL AND DateIn >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T05:13:57.315805+00:00", "question": "loads today", "generated_sql": "", "summary": "by hour of day.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T05:15:21.045133+00:00", "question": "loads today", "generated_sql": "", "summary": "by company.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T05:20:05.193354+00:00", "question": "how many loads today", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:20:27.141745+00:00", "question": "how many loads today", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text."}}
{"timestamp": "2025-10-18T05:20:39.737262+00:00", "question": "how many loads today", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text."}}
{"timestamp": "2025-10-18T05:20:41.659656+00:00", "question": "how many loads today", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text."}}
{"timestamp": "2025-10-18T05:23:08.515321+00:00", "question": "how many loads yesterday", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": null, "llm_warning": null}}
{"timestamp": "2025-10-18T05:27:15.090465+00:00", "question": "how many loads today", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model did not return a valid SELECT statement; execution skipped."}}
{"timestamp": "2025-10-18T05:27:26.874405+00:00", "question": "how many loads today", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:27:36.059809+00:00", "question": "how many loads today", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model did not return a valid SELECT statement; execution skipped."}}
{"timestamp": "2025-10-18T05:27:49.287435+00:00", "question": "how many loads today", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model did not return a valid SELECT statement; execution skipped."}}
{"timestamp": "2025-10-18T05:31:49.883529+00:00", "question": "how many loads today", "generated_sql": "?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:32:13.445086+00:00", "question": "how many loads yesterday", "generated_sql": "?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:34:47.617732+00:00", "question": "how many loads yesterday", "generated_sql": "?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:35:08.187517+00:00", "question": "how many loads yesterday", "generated_sql": "?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:35:33.179333+00:00", "question": "loads yesterday", "generated_sql": ".\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:35:48.883049+00:00", "question": "loads yesterday", "generated_sql": ".\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:36:57.638273+00:00", "question": "loads yesterday", "generated_sql": ".\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:37:03.365771+00:00", "question": "loads yesterday", "generated_sql": ".\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:37:23.700969+00:00", "question": "loads today", "generated_sql": "by company.\n SQL: SELECT TCompanyName, COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date) GROUP BY TCompanyName;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:38:23.520274+00:00", "question": "how many loads today", "generated_sql": "?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date) AND DateOut < CAST(SYSDATETIME() AS date) + INTERVAL '1 day';", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:41:26.380665+00:00", "question": "how many loads today", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:41:43.575137+00:00", "question": "how many loads yesterday", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:42:01.397903+00:00", "question": "how many sugar loads yesterday", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar';", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:42:30.020874+00:00", "question": "how many sugar loads monday", "generated_sql": "to friday?\n SQL: SELECT COUNT(*) AS total_loads FROM dbo.SugarLoadData WHERE EXTRACT(dow FROM DateOut) BETWEEN 1 AND 5 AND CAST(DateOut AS DATE) = CAST(SYSDATETIME() AS DATE);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:43:13.781796+00:00", "question": "how many sugar loads this past monday", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -7, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar';", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -7, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:43:28.190660+00:00", "question": "how many sugar loads this past tuesday", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar';", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:44:06.905858+00:00", "question": "what was the heaviest load this week?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, -1, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, -1, CAST(SYSDATETIME() AS date))", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:44:23.020379+00:00", "question": "what was the heaviest load last week?", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME());", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:44:34.759816+00:00", "question": "what was the heaviest load this week?", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, -1, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, -1, CAST(SYSDATETIME() AS date))", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:45:18.288731+00:00", "question": "what was the heaviest load from 10/1 to 10/18?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2020-10-01' AND '2020-10-18';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2020-10-01' AND '2020-10-18'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:45:31.894904+00:00", "question": "what was the heaviest load from 10/1 to 10/18?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2020-10-01' AND '2020-10-18';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2020-10-01' AND '2020-10-18'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:46:35.269288+00:00", "question": "what was the heaviest load from 10/1/25 to 10/18/25?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-18';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-18'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:46:55.001426+00:00", "question": "what was the lightest load from 10/1/25 to 10/18/25?", "generated_sql": "", "summary": "{\"generated_text\":\"\"}", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "LLM response missing generated_text field; returning raw text. Preview: {\"generated_text\":\"\"} Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:47:05.775303+00:00", "question": "what was the lightest load from 10/1/25 to 10/18/25?", "generated_sql": "", "summary": "{\"generated_text\":\"\"}", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "LLM response missing generated_text field; returning raw text. Preview: {\"generated_text\":\"\"} Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:47:32.286521+00:00", "question": "what was the heaviest load from 10/1/25 to 10/9/25?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-09';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-09'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:47:49.570488+00:00", "question": "what was the heaviest load from 10/1/25 to 10/3/25?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-03';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-03'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:48:03.258613+00:00", "question": "what was the heaviest load from 10/4/25 to 10/6/25?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-04' AND '2025-10-06';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-04' AND '2025-10-06'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:48:17.686387+00:00", "question": "what was the heaviest load from 10/4/25 to 10/5/25?", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-04' AND '2025-10-05';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-04' AND '2025-10-05'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:48:32.284279+00:00", "question": "what was the heaviest load from 10/7/25 to 10/9/25?", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-07' AND '2025-10-09';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-07' AND '2025-10-09'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:24:00.713687+00:00", "question": "How many loads over 100000 yesterday", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND GrossWt > 100000;", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND GrossWt > 100000", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:24:22.328815+00:00", "question": "List all loads over 100000 yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE GrossWt > 100000 AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) * FROM dbo.SugarLoadData WHERE GrossWt > 100000 AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 6, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:25:13.769895+00:00", "question": "List all loads over 100000 yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND GrossWt > 100000;", "summary": "", "sanitized_sql": "SELECT TOP (500) * FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND GrossWt > 100000", "row_count": 6, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:25:47.952375+00:00", "question": "List all loads between 90000 and 80000 yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE ScaleWT BETWEEN 90000 AND 80000 AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime);", "summary": "", "sanitized_sql": "SELECT TOP (500) * FROM dbo.SugarLoadData WHERE ScaleWT BETWEEN 90000 AND 80000 AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)", "row_count": 0, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:26:25.273525+00:00", "question": "List all loads between 90000 and 100000 yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE ScaleWT BETWEEN 90000 AND 100000 AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) ORDER BY DateOut NULLS LAST;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:26:57.761426+00:00", "question": "List all loads from yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:27:05.021191+00:00", "question": "List all loads from yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) * FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 22, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Initial attempt failed: LLM output could not be parsed; returning raw text. Preview: .. Retried with formatting reminder."}}
{"timestamp": "2025-10-18T14:27:45.472453+00:00", "question": "List all loads from 10/16/25", "generated_sql": "", "summary": "to 10/17/25.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: to 10/17/25. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:28:01.189092+00:00", "question": "List all loads from 10/16/25", "generated_sql": "", "summary": "00 to 10/17/2500.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: 00 to 10/17/2500. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:39:53.987644+00:00", "question": "List all loads from 10/16/25", "generated_sql": "", "summary": "62 to 10/17/2562.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: 62 to 10/17/2562. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:40:19.791577+00:00", "question": "List all loads from monday", "generated_sql": "to friday.\n SQL: SELECT * FROM dbo.SugarLoadData WHERE EXTRACT(dow FROM DateOut) BETWEEN 1 AND 5;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:40:57.479412+00:00", "question": "List all loads from 10/15/25", "generated_sql": "", "summary": "62 to 10/20/2562.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: 62 to 10/20/2562. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:41:18.647455+00:00", "question": "List all loads from 10/15/2025", "generated_sql": "to 10/20/2025.\n SQL: SELECT * FROM dbo.SugarLoadData WHERE DateIn BETWEEN '2025-10-15' AND '2025-10-20';", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:41:49.205697+00:00", "question": "List all loads from 10/15/2025 only", "generated_sql": "", "summary": ".", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: . Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:42:15.314362+00:00", "question": "List all loads from the past week", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) * FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date))", "row_count": 233, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Initial attempt failed: LLM output could not be parsed; returning raw text. Preview: .. Retried with formatting reminder."}}
{"timestamp": "2025-10-18T14:43:27.908517+00:00", "question": "List all loads from ralph callier", "generated_sql": "'s company in the last 24 hours.\n SQL: SELECT * FROM dbo.SugarLoadData l WHERE l.TCompanyName ILIKE '%RALPH%CALLIER%' AND l.DateOut >= DATEADD(hour, -24, SYSDATETIME()) ORDER BY l.DateOut NULLS LAST;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:50:03.104069+00:00", "question": "List all loads from ralph callier", "generated_sql": "'s company in the last 24 hours.\n SQL: SELECT * FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE v.TCompanyName ILIKE '%ralph%callier%' AND l.DateOut >= DATEADD(hour, -24, SYSDATETIME()) ORDER BY l.DateOut NULLS LAST;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:50:42.250044+00:00", "question": "List all loads from company ralph callier", "generated_sql": "in the last 24 hours.\n SQL: SELECT * FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%ralph%callier%' AND DateOut >= CAST(DATEADD(hour, -24, CAST(SYSDATETIME() AS date)) AS datetime) ORDER BY DateOut NULLS LAST;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:51:04.350689+00:00", "question": "List all loads from company Ralph Callier", "generated_sql": "in the last 7 days.\n SQL: SELECT * FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%Ralph%Callier%' AND DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:51:50.844953+00:00", "question": "List all loads from company Ralph Callier", "generated_sql": "in the last 7 days.\n SQL: SELECT * FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%Ralph%Callier%' AND DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T16:54:56.079797+00:00", "question": "How many loads from Ralph callier", "generated_sql": "were delivered in the last 24 hours?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(hour, -24, CAST(SYSDATETIME() AS date)) AND TCompanyName ILIKE '%Ralph%callier%';", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T16:59:27.498329+00:00", "question": "How many loads from Ralph callier", "generated_sql": "were delivered yesterday?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND TCompanyName ILIKE '%Ralph%callier%';", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T16:59:55.618771+00:00", "question": "How many loads from Ralph callier from all time", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": null, "llm_warning": "LLM output could not be parsed; returning raw text. Preview: ? Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T17:00:04.917741+00:00", "question": "How many loads from Ralph callier from all time", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: ? Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T17:00:12.836444+00:00", "question": "How many loads from Ralph callier from all time", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: ? Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T17:00:24.283622+00:00", "question": "How many loads from Ralph callier", "generated_sql": "were delivered today?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date) AND TCompanyName ILIKE '%Ralph%callier%';", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T17:00:46.640184+00:00", "question": "How many loads from Ralph callier", "generated_sql": "were delivered today?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%Ralph%callier%' AND DateOut >= CAST(SYSDATETIME() AS date) AND DateOut < CAST(SYSDATETIME() + INTERVAL '1 day' AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T17:01:06.370459+00:00", "question": "How many loads from Ralph callier were delivered today", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%Ralph%callier%' AND DateOut >= CAST(SYSDATETIME() AS date) AND DateOut < CAST(SYSDATETIME() + INTERVAL '1 day' AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Initial attempt failed: LLM output could not be parsed; returning raw text. Preview: ?. Retried with formatting reminder."}}
{"timestamp": "2025-10-18T19:09:05.990023+00:00", "question": "Find loads from Ralph Callier", "generated_sql": "'s company in the last 24 hours.\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE v.TCompanyName ILIKE '%Ralph%Callier%' AND l.DateOut >= DATEADD(hour, -24, SYSDATETIME());", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model added an unrequested time filter. Ensure future responses only add filters present in the question. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T19:20:37.648813+00:00", "question": "Find loads from Ralph Callier", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%RALPH CALLIER%' AND DateOut >= CAST(DATEADD(day, -14, SYSDATETIME()) AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T19:25:07.932494+00:00", "question": "Find loads from Ralph Callier", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE UPPER(v.TCompanyName) LIKE UPPER('%RALPH%CALLIER%') AND l.DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE UPPER(v.TCompanyName) LIKE UPPER('%RALPH%CALLIER%') AND l.DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T19:25:33.393615+00:00", "question": "Find loads from ralph callier", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE UPPER(v.TCompanyName) LIKE UPPER('%ralph%callier%') AND l.DateOut IS NOT NULL;", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE UPPER(v.TCompanyName) LIKE UPPER('%ralph%callier%') AND l.DateOut IS NOT NULL", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T19:26:17.092654+00:00", "question": "Lost all loads from ralph callier", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE UPPER(TCompanyName) LIKE UPPER('%RALPH%CALLIER%') AND DateOut IS NULL;", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE UPPER(TCompanyName) LIKE UPPER('%RALPH%CALLIER%') AND DateOut IS NULL", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Attempt 1: LLM output could not be parsed; returning raw text. Preview: .; Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T22:38:21.424656+00:00", "question": "How many loads of sugar today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\n Summary: \"There are currently 0 loads of sugar today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": null, "llm_warning": null}}
{"timestamp": "2025-10-18T22:38:55.851817+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\n Summary: \"There are currently 0 loads today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": null, "llm_warning": null}}
{"timestamp": "2025-10-18T22:41:12.118065+00:00", "question": "How many loads today from ralph callier", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)\n AND UPPER(TCompanyName) LIKE UPPER('%ralph callier%');\n Summary: \"There are 0 loads today from Ralph Callier.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": null, "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T22:41:19.813140+00:00", "question": "How many loads today from ralph callier", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)\n AND UPPER(TCompanyName) LIKE UPPER('%ralph callier%');\n Summary: \"There are currently 0 loads from Ralph Callier today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T22:44:22.833620+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\n Summary: \"There are currently 0 loads today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:44:40.809277+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\n Summary: \"There are currently 0 loads today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:45:09.238103+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\n Summary: \"There are currently 0 loads today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:47:17.025283+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "There are currently 0 loads today.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:47:22.458532+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "There are currently 0 loads today.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:47:40.158932+00:00", "question": "How many loads yesterday", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "There were 5 loads completed yesterday.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:48:13.677738+00:00", "question": "Liat all loads from ralph callier", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"TCompanyName\" ILIKE '%RALPH CALLIER%';", "summary": "Retrieving all load data for 'RALPH CALLIER'.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:48:55.477012+00:00", "question": "Liat all loads from ralph callier", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"TCompanyName\" ILIKE '%RALPH CALLIER%';", "summary": "Retrieving all load data for 'RALPH CALLIER'.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:50:52.444577+00:00", "question": "Liat all loads from ralph callier", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%RALPH CALLIER%');", "summary": "Retrieving all load data for 'RALPH CALLIER'.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T22:51:05.166730+00:00", "question": "Liat all loads from ralph callier", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%RALPH CALLIER%');", "summary": "Retrieving all load data for 'RALPH CALLIER'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%RALPH CALLIER%')", "row_count": 67, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T22:51:56.087879+00:00", "question": "Liat all loads from 10/12/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00';", "summary": "Retrieving all loads that occurred on 10/12/25.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'", "row_count": 16, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:52:17.374235+00:00", "question": "Liat all loads from 10/12/25 over 100000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND GrossWt > 100000;", "summary": "Retrieving all loads that occurred on or after 10/12/25 and had a gross weight over 100000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND GrossWt > 100000", "row_count": 23, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:52:59.798088+00:00", "question": "Liat all loads from 10/12/25 to 10/13/25 over 100000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00' AND DateOut < '2025-10-14 00:00:00' AND GrossWt > 100000;", "summary": "Selecting all loads from 10/12/25 to 10/13/25 with a gross weight over 100000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00' AND DateOut < '2025-10-14 00:00:00' AND GrossWt > 100000", "row_count": 6, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T23:15:45.718718+00:00", "question": "How many loads over 100000", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE GrossWt > 100000;\n Summary: \"There are 0 loads over 100000.\"", "summary": "", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE GrossWt > 100000;\\n Summary: \\\"There are 0 loads over 100000.\\\"\", \"summary\": \"\", \"llm_warning\": \"Attempt 1: Model response did not include a valid SELECT statement.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Attempt 1: Model response did not include a valid SELECT statement."}}
{"timestamp": "2025-10-18T23:18:13.423493+00:00", "question": "How many loads over 100000", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE GrossWt > 100000;", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE GrossWt > 100000", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE GrossWt > 100000;\", \"summary\": \"\", \"llm_warning\": \"Postprocess: Removed unrequested date/time filters from SQL output.; Attempt 1: Model response did not include a valid SELECT statement.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Removed unrequested date/time filters from SQL output.; Attempt 1: Model response did not include a valid SELECT statement."}}
{"timestamp": "2025-10-19T00:19:34.490018+00:00", "question": "List all loads on 10/12/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00';", "summary": "The SQL query lists all loads that occurred on October 12, 2025.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-13 00:00:00';\", \"summary\": \"The SQL query lists all loads that occurred on October 12, 2025.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T00:20:36.968497+00:00", "question": "List all loads on 10/12/25 hauled by big dog", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%big dog%')\n );", "summary": "The SQL query lists all loads that occurred on 10/12/25 and were hauled by vehicles associated with the company name 'Big Dog'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%big dog%')\n )", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-13 00:00:00'\\n AND VehicleId_Fk IN (\\n SELECT VehicleId_Pk\\n FROM dbo.SugarVehicles\\n WHERE UPPER(TCompanyName) LIKE UPPER('%big dog%')\\n );\", \"summary\": \"The SQL query lists all loads that occurred on 10/12/25 and were hauled by vehicles associated with the company name 'Big Dog'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T00:20:50.601977+00:00", "question": "List all loads on 10/12/25 hauled by bigdog", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdog%')\n );", "summary": "The SQL query lists all loads that occurred on 10/12/25 and were hauled by vehicles associated with the company name 'bigdog'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdog%')\n )", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-13 00:00:00'\\n AND VehicleId_Fk IN (\\n SELECT VehicleId_Pk\\n FROM dbo.SugarVehicles\\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdog%')\\n );\", \"summary\": \"The SQL query lists all loads that occurred on 10/12/25 and were hauled by vehicles associated with the company name 'bigdog'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T00:21:21.343228+00:00", "question": "List all loads on 10/12/25 hauled by csc", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%csc%');", "summary": "The SQL query lists all loads that occurred on 10/12/25 and were hauled by 'csc'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%csc%')", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-13 00:00:00'\\n AND UPPER(TCompanyName) LIKE UPPER('%csc%');\", \"summary\": \"The SQL query lists all loads that occurred on 10/12/25 and were hauled by 'csc'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T00:53:01.274866+00:00", "question": "List all loads on 10/14/25 hauled by csc", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%csc%');", "summary": "The SQL query lists all loads that occurred on 10/14/25 and were hauled by 'csc'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%csc%')", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-14 00:00:00'\\n AND DateOut < '2025-10-15 00:00:00'\\n AND UPPER(TCompanyName) LIKE UPPER('%csc%');\", \"summary\": \"The SQL query lists all loads that occurred on 10/14/25 and were hauled by 'csc'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T00:54:53.249509+00:00", "question": "List all loads that have gs in the vehicle name", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%gs%')\n );", "summary": "Retrieving all loads associated with vehicles whose company names contain 'gs'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%gs%')\n )", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (\\n SELECT VehicleId_Pk\\n FROM dbo.SugarVehicles\\n WHERE UPPER(TCompanyName) LIKE UPPER('%gs%')\\n );\", \"summary\": \"Retrieving all loads associated with vehicles whose company names contain 'gs'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T00:55:32.113502+00:00", "question": "List all loads that have gs in the vehicle id", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%gs%';", "summary": "Retrieving all loads with 'gs' in the vehicle id.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%gs%'", "row_count": 71, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk LIKE '%gs%';\", \"summary\": \"Retrieving all loads with 'gs' in the vehicle id.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T00:56:02.539411+00:00", "question": "List all loads that have callier in the vehicle id", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%callier%';", "summary": "Retrieving all load data for vehicles with 'callier' in their identifier.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%callier%'", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk LIKE '%callier%';\", \"summary\": \"Retrieving all load data for vehicles with 'callier' in their identifier.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T00:56:21.164487+00:00", "question": "List all loads that have laca in the vehicle id", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%laca%';", "summary": "Retrieving all loads with 'laca' in the vehicle ID.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%laca%'", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk LIKE '%laca%';\", \"summary\": \"Retrieving all loads with 'laca' in the vehicle ID.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T00:57:41.163029+00:00", "question": "List all loads that have bd in the vehicle id", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%bd%';", "summary": "Retrieving all load data for vehicles with 'bd' in their identifier.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%bd%'", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk LIKE '%bd%';\", \"summary\": \"Retrieving all load data for vehicles with 'bd' in their identifier.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T00:58:56.525276+00:00", "question": "List all loads that are between 90000 and 92000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE GrossWt BETWEEN 90000 AND 92000;", "summary": "Listing all loads with gross weights between 90000 and 92000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE GrossWt BETWEEN 90000 AND 92000", "row_count": 88, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE GrossWt BETWEEN 90000 AND 92000;\", \"summary\": \"Listing all loads with gross weights between 90000 and 92000.\", \"llm_warning\": \"Attempt 1: Model response did not include a valid SELECT statement.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Attempt 1: Model response did not include a valid SELECT statement."}}
{"timestamp": "2025-10-19T01:07:11.573000+00:00", "question": "List all loads that are between 90000 and 92000\nAnd the company is bigdawg", "generated_sql": "SELECT *\nFROM dbo.SugarLoadData\nWHERE GrossWt BETWEEN 90000 AND 92000\n AND UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%');", "summary": "The SQL query lists all loads with a gross weight between 90000 and 92000 and the company name contains 'BIGDAWG'.", "sanitized_sql": "SELECT TOP (500) *\nFROM dbo.SugarLoadData\nWHERE GrossWt BETWEEN 90000 AND 92000\n AND UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%')", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\nFROM dbo.SugarLoadData\\nWHERE GrossWt BETWEEN 90000 AND 92000\\n AND UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%');\", \"summary\": \"The SQL query lists all loads with a gross weight between 90000 and 92000 and the company name contains 'BIGDAWG'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T01:15:17.775803+00:00", "question": "List all loads with a tare weight less than 30000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000;", "summary": "Retrieving all load data with a tare weight less than 30000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE \\\"TareWt\\\" < 30000;\", \"summary\": \"Retrieving all load data with a tare weight less than 30000.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T01:31:27.548741+00:00", "question": "Show me all loads under 30000", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\n FROM dbo.SugarLoadData\n WHERE GrossWt < 30000;", "summary": "Displaying all load data with a gross weight less than 30000 pounds.", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\\n FROM dbo.SugarLoadData\\n WHERE GrossWt < 30000;\", \"summary\": \"Displaying all load data with a gross weight less than 30000 pounds.\", \"llm_warning\": \"Attempt 1: Model response did not include a valid SELECT statement.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Attempt 1: Model response did not include a valid SELECT statement."}}
{"timestamp": "2025-10-19T01:31:39.506732+00:00", "question": "Show me all loads under 30000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE GrossWt < 30000;", "summary": "Displaying all loads with a gross weight less than 30000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE GrossWt < 30000", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE GrossWt < 30000;\", \"summary\": \"Displaying all loads with a gross weight less than 30000.\", \"llm_warning\": \"Attempt 1: Model response did not include a valid SELECT statement.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Attempt 1: Model response did not include a valid SELECT statement."}}
{"timestamp": "2025-10-19T01:32:54.438627+00:00", "question": "Show me all loads with a tare under 30000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000;", "summary": "Retrieving all load data with a tare weight less than 30000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE \\\"TareWt\\\" < 30000;\", \"summary\": \"Retrieving all load data with a tare weight less than 30000.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T01:33:08.391754+00:00", "question": "Show me all loads with a tare under 30000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000;", "summary": "Retrieving all load data with a tare weight less than 30000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-19T02:16:49.993593+00:00", "question": "show me loads hauled by bigdawg between 10/12/25 and 10/14/25", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\n ORDER BY DateIn;", "summary": "The SQL query retrieves load data for loads hauled by 'BIGDAWG' between 10/12/25 and 10/14/25, ordered by the time of entry.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\n ORDER BY DateIn", "row_count": 17, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\\n ORDER BY DateIn;\", \"summary\": \"The SQL query retrieves load data for loads hauled by 'BIGDAWG' between 10/12/25 and 10/14/25, ordered by the time of entry.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:17:40.030692+00:00", "question": "show me loads hauled by bigdawg between 10/12/25 and 10/14/25 that are over 100000", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'\n AND GrossWt > 100000;", "summary": "Bigdawg has hauled 100000+ pound loads on 10/12/25 and 10/13/25.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'\n AND GrossWt > 100000", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, DateOut\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-15 00:00:00'\\n AND GrossWt > 100000;\", \"summary\": \"Bigdawg has hauled 100000+ pound loads on 10/12/25 and 10/13/25.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:18:03.083340+00:00", "question": "show me loads hauled by bigdawg between 10/12/25 and 10/14/25 that have a tare less than 30000", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\n )\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\n AND TareWt < 30000;", "summary": "Bigdawg loads with a tare less than 30000 from 10/12/25 to 10/14/25 are being listed.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\n )\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\n AND TareWt < 30000", "row_count": 2, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (\\n SELECT VehicleId_Pk\\n FROM dbo.SugarVehicles\\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\\n )\\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\\n AND TareWt < 30000;\", \"summary\": \"Bigdawg loads with a tare less than 30000 from 10/12/25 to 10/14/25 are being listed.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:18:21.655909+00:00", "question": "show me loads hauled by bigdawg between 10/12/25 and 10/14/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-15 00:00:00';", "summary": "The SQL query retrieves all loads associated with vehicles registered to 'BIGDAWG' that occurred between 10/12/25 and 10/14/25.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-15 00:00:00';\", \"summary\": \"The SQL query retrieves all loads associated with vehicles registered to 'BIGDAWG' that occurred between 10/12/25 and 10/14/25.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:19:17.123783+00:00", "question": "show me loads hauled by bigdawg on 10/12/25 between 6am and noon", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 06:00:00'\n AND DateOut < '2025-10-12 12:00:00';", "summary": "The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' that occurred between 6am and noon on 10/12/25.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 06:00:00'\n AND DateOut < '2025-10-12 12:00:00'", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-12 06:00:00'\\n AND DateOut < '2025-10-12 12:00:00';\", \"summary\": \"The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' that occurred between 6am and noon on 10/12/25.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:19:34.232102+00:00", "question": "show me loads hauled by bigdawg on 10/12/25 between 6am and 12pm", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 06:00:00'\n AND DateOut < '2025-10-12 12:00:00';", "summary": "Here are the loads hauled by 'BIGDAWG' on 10/12/25 from 6am to 12pm.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 06:00:00'\n AND DateOut < '2025-10-12 12:00:00'", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-12 06:00:00'\\n AND DateOut < '2025-10-12 12:00:00';\", \"summary\": \"Here are the loads hauled by 'BIGDAWG' on 10/12/25 from 6am to 12pm.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:20:16.725795+00:00", "question": "show me loads hauled by bigdawg on 10/12/25 between 12am and 11pm", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 23:00:00';", "summary": "The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' from 10/12/25 from 12am to 11pm.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 23:00:00'", "row_count": 11, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-13 23:00:00';\", \"summary\": \"The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' from 10/12/25 from 12am to 11pm.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:21:20.618815+00:00", "question": "show me loads hauled by bigdawg on 10/13/25 between midnight and 4pm", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-13 16:00:00';", "summary": "The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' on October 13, 2025, between midnight and 4pm.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-13 16:00:00'", "row_count": 6, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-13 00:00:00'\\n AND DateOut < '2025-10-13 16:00:00';\", \"summary\": \"The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' on October 13, 2025, between midnight and 4pm.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}

View File

@@ -0,0 +1,33 @@
# Prompt Assembly
Utilities for packaging database context into a single LLM prompt.
## Files
- `prompt_builder.py`: Loads schema/glossary/value hints/example artifacts and produces a structured prompt for SQL generation.
- `__init__.py`: Exposes `load_context` and `build_prompt` helpers.
## Quick Start
1. Ensure context artifacts exist under `db_agent/context/` (run the extractor, curate glossary/value hints/examples).
2. In Python, build the prompt:
```python
from db_agent.prompting import load_context, build_prompt
ctx = load_context()
prompt = build_prompt(
question="Which vehicles hauled more than 30 tons last week?",
context=ctx,
table_hints=["dbo.SugarLoadData", "dbo.SugarVehicles"],
)
print(prompt)
```
3. Send the prompt to your LLM provider (OpenAI, Azure OpenAI, Anthropic, etc.) and parse the JSON response with the `sql` and `summary` fields.
## Configuration
- Customize file paths by instantiating `PromptConfig` with alternate filenames or directories.
- Use `table_hints` to restrict the schema section to relevant tables (helps stay within context limits).
- Adjust `max_columns` to control how many column definitions are emitted per table.
## Next Steps
- Integrate the prompt builder into a service layer that calls the LLM and executes the generated SQL with validation.
- Add retrieval heuristics to automatically pick tables based on keyword matching instead of manually passing `table_hints`.
- Extend the format to include recent query logs or execution feedback for reinforcement.

View File

@@ -0,0 +1,10 @@
"""Prompt assembly utilities for the database agent."""
from .prompt_builder import AgentContext, PromptConfig, build_prompt, load_context
__all__ = [
"AgentContext",
"PromptConfig",
"build_prompt",
"load_context",
]

View File

@@ -0,0 +1,190 @@
"""Assemble LLM prompts for natural-language SQL generation."""
from __future__ import annotations
import json
import textwrap
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence
import yaml
@dataclass(frozen=True)
class PromptConfig:
"""File layout for context artifacts consumed by the prompt builder."""
context_dir: Path = field(default_factory=lambda: Path("db_agent/context"))
schema_filename: str = "schema.json"
glossary_filename: str = "glossary.md"
value_hints_filename: str = "value_hints.yaml"
examples_filename: str = "examples.json"
@dataclass
class AgentContext:
"""Loaded context assets ready for prompt rendering."""
schema: Dict[str, Any]
glossary_markdown: str
value_hints: Dict[str, Any]
examples: List[Dict[str, Any]]
def load_context(config: PromptConfig | None = None) -> AgentContext:
"""Load the canonical context files from disk."""
cfg = config or PromptConfig()
base = cfg.context_dir
schema_path = base / cfg.schema_filename
glossary_path = base / cfg.glossary_filename
value_hints_path = base / cfg.value_hints_filename
examples_path = base / cfg.examples_filename
schema = json.loads(schema_path.read_text(encoding="utf-8"))
glossary_markdown = glossary_path.read_text(encoding="utf-8")
value_hints = yaml.safe_load(value_hints_path.read_text(encoding="utf-8")) or {}
examples = json.loads(examples_path.read_text(encoding="utf-8"))
return AgentContext(
schema=schema,
glossary_markdown=glossary_markdown,
value_hints=value_hints,
examples=examples,
)
def _format_table(table_key: str, table_doc: Dict[str, Any], max_columns: int) -> str:
"""Render a single table definition block."""
lines: List[str] = [f"Table {table_key}: {table_doc.get('schema')}.{table_doc.get('name')}"]
column_docs = table_doc.get("columns", [])
for idx, column in enumerate(column_docs):
if idx >= max_columns:
lines.append(f" ... ({len(column_docs) - max_columns} more columns omitted)")
break
col_line = f" - {column['name']} ({column['type']})"
if column.get("nullable") is False:
col_line += " NOT NULL"
if column.get("default") not in (None, ""):
col_line += f" DEFAULT {column['default']}"
lines.append(col_line)
relationships = table_doc.get("relationships", [])
if relationships:
lines.append(" Relationships:")
for rel in relationships:
target = rel.get("target")
src_col = rel.get("source_column")
tgt_col = rel.get("target_column")
lines.append(f" * {src_col} -> {target}.{tgt_col}")
return "\n".join(lines)
def _format_schema(schema_doc: Dict[str, Any], include_tables: Optional[Sequence[str]], max_columns: int) -> str:
"""Render the subset of tables to include in the prompt."""
table_section: List[str] = []
tables = schema_doc.get("tables", {})
def table_selected(table_key: str, table_doc: Dict[str, Any]) -> bool:
if not include_tables:
return True
candidates = {table_key, table_doc.get("name"), f"{table_doc.get('schema')}.{table_doc.get('name')}"}
return any(name in include_tables for name in candidates if name)
for table_key, table_doc in tables.items():
if table_selected(table_key, table_doc):
table_section.append(_format_table(table_key, table_doc, max_columns=max_columns))
if not table_section:
return "(No tables selected; broaden include_tables to see schema context.)"
return "\n\n".join(table_section)
def _format_examples(examples: Iterable[Dict[str, Any]]) -> str:
"""Render examples as numbered items for clarity."""
lines: List[str] = []
for idx, example in enumerate(examples, start=1):
question = example.get("question", "(missing question)")
sql = example.get("sql", "-- SQL not provided")
notes = example.get("notes")
lines.append(f"Example {idx}: {question}")
lines.append("SQL:\n" + sql)
if notes:
lines.append(f"Notes: {notes}")
lines.append("")
return "\n".join(lines).strip()
def _format_value_hints(hints: Dict[str, Any]) -> str:
"""Dump value hints to YAML for prompt readability."""
if not hints:
return "(No value hints available.)"
return yaml.safe_dump(hints, sort_keys=False, allow_unicode=False)
def build_prompt(
question: str,
context: AgentContext,
table_hints: Optional[Sequence[str]] = None,
max_columns: int = 12,
format_hint: Optional[str] = None,
) -> str:
"""Compose the full system + user prompt for the SQL agent."""
schema_section = _format_schema(context.schema, include_tables=table_hints, max_columns=max_columns)
examples_section = _format_examples(context.examples)
value_hints_section = _format_value_hints(context.value_hints)
additional_instructions = ""
if format_hint:
additional_instructions = f"\n ### Additional Formatting Instructions\n {format_hint}\n"
prompt = textwrap.dedent(
f"""You are an assistant that translates operator questions into safe T-SQL for SQL Server.
Follow these rules:
- Use SELECT statements only; never modify data.
- Apply TOP or date filters only when explicitly requested or when needed to respect the max_rows limit; never infer time windows that the user did not mention.
- Reference fully qualified table names with schema (e.g., dbo.TableName).
- Use SQL Server date/time functions: prefer CONVERT(date, ...), CAST(... AS date), DATEPART, DATEADD, DATEDIFF. Do not use MySQL/Postgres functions like DATE(), EXTRACT(), or INTERVAL literals.
- Stick to SQL Server syntax: use LIKE (and optionally UPPER/LTRIM/RTRIM) instead of ILIKE; avoid LIMIT/OFFSET, NULLS FIRST/LAST, USING, or other non-T-SQL constructs.
- Only include literals or filters grounded in the question or provided hints; do not fabricate IDs, random suffixes, or placeholder strings.
- Every filter must be justified by the user question: "{question}". If the question does not reference a timeframe, do not add one. If unsure, return an empty sql value and ask for clarification in the summary.
- If information is missing, ask for clarification instead of guessing.
### Database Schema
{schema_section}
### Business Glossary
{context.glossary_markdown.strip()}
### Value Hints
{value_hints_section.strip()}
### Worked Examples
{examples_section}
### Task
Generate a SQL query that answers the user question and summarize the answer in natural language.
Return ONLY a JSON object with the following structure (no code fences, no extra commentary):
{{"sql": "<the SQL query>", "summary": "<one sentence summary>"}}
{additional_instructions}
User question: {question}
"""
).strip()
return prompt
__all__ = [
"PromptConfig",
"AgentContext",
"load_context",
"build_prompt",
]

View File

@@ -0,0 +1,7 @@
sqlalchemy>=2.0,<3.0
pyodbc>=5.0,<6.0
PyYAML>=6.0,<7.0
requests>=2.31,<3.0
urllib3>=1.26,<2.0
fastapi>=0.111,<1.0
uvicorn[standard]>=0.30,<1.0

View File

@@ -0,0 +1,140 @@
"""Example entry point for running a natural-language SQL query."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from typing import Optional
from .client import SqlAgentClient, default_client
from .log_utils import log_interaction
from .sql_executor import SqlExecutionResult, SqlValidationError, execute_sql
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Run a question through the SQL agent.")
parser.add_argument("question", help="Natural language question to transform into SQL.")
parser.add_argument(
"--tables",
nargs="*",
default=None,
help="Optional list of tables to prioritize (e.g., dbo.SugarLoadData).",
)
parser.add_argument(
"--output",
type=str,
default=None,
help="Optional path to write the raw LLM JSON response.",
)
parser.add_argument(
"--execute",
action="store_true",
help="Validate and run the generated SQL against MSSQL.",
)
parser.add_argument(
"--max-rows",
type=int,
default=500,
help="Maximum rows to fetch; enforced via TOP clause when executing.",
)
parser.add_argument(
"--log-path",
type=str,
default=None,
help="Append interaction logs to this JSONL file (defaults to db_agent/logs/query_log.jsonl).",
)
parser.add_argument(
"--no-log",
action="store_true",
help="Disable interaction logging.",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
client: SqlAgentClient = default_client()
response = client.query(question=args.question, table_hints=args.tables)
if args.output:
with open(args.output, "w", encoding="utf-8") as fp:
json.dump(response, fp, indent=2)
print(f"Response written to {args.output}")
else:
print(json.dumps(response, indent=2))
generated_sql = response.get("sql", "").strip()
summary = response.get("summary", "").strip()
execution_result: Optional[SqlExecutionResult] = None
normalized_sql = generated_sql.lstrip()
sql_is_select = normalized_sql.lower().startswith("select") if normalized_sql else False
execution_warning: Optional[str] = None
execution_status: Optional[str] = None
execution_error: Optional[str] = None
if args.execute:
if not normalized_sql:
execution_warning = "No SQL returned; skipping execution."
print(execution_warning)
elif not sql_is_select:
execution_warning = "Generated SQL is not a SELECT statement; skipping execution."
print(execution_warning)
else:
try:
execution_result = execute_sql(normalized_sql, max_rows=args.max_rows)
except SqlValidationError as exc:
execution_warning = f"SQL validation failed: {exc}"
execution_error = str(exc)
print(f"SQL validation failed: {exc}")
except Exception as exc:
execution_error = str(exc)
print(f"SQL execution failed: {exc}")
raise
else:
execution_status = "success"
print("Sanitized SQL:")
print(execution_result.sql)
print(f"Rows returned: {len(execution_result.rows)}")
if execution_result.rows:
preview = execution_result.rows[: min(5, len(execution_result.rows))]
print("Preview (up to 5 rows):")
print(json.dumps(preview, indent=2, default=str))
if not args.no_log:
log_path = Path(args.log_path) if args.log_path else None
metadata = {
"tables_hint": args.tables,
"execution_requested": args.execute,
}
if execution_result:
metadata.update(
{
"columns": execution_result.columns,
"preview_rows": min(5, len(execution_result.rows)),
}
)
if execution_warning:
metadata["execution_warning"] = execution_warning
log_interaction(
question=args.question,
generated_sql=generated_sql,
summary=summary,
sanitized_sql=execution_result.sql if execution_result else None,
row_count=len(execution_result.rows) if execution_result else None,
execution_status=execution_status,
execution_error=execution_error,
raw_response=json.dumps(response, ensure_ascii=False),
log_path=log_path,
metadata=metadata,
)
if log_path:
print(f"Interaction appended to {log_path}")
else:
print("Interaction appended to db_agent/logs/query_log.jsonl")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,140 @@
"""Validation and execution helpers for generated SQL queries."""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any, Dict, List, Sequence
import sqlalchemy as sa
from sqlalchemy.engine import Engine
from .extractor.settings import DbSettings
class SqlValidationError(RuntimeError):
"""Raised when a generated SQL statement fails safety checks."""
PROHIBITED_KEYWORDS: Sequence[str] = (
"INSERT",
"UPDATE",
"DELETE",
"MERGE",
"DROP",
"ALTER",
"TRUNCATE",
"CREATE",
"EXEC",
"EXECUTE",
"GRANT",
"REVOKE",
"BEGIN",
"COMMIT",
"ROLLBACK",
)
UNSUPPORTED_PATTERNS: Sequence[str] = (
r"\bILIKE\b",
r"NULLS\s+LAST",
r"NULLS\s+FIRST",
r"\bLIMIT\b",
r"\bOFFSET\b",
r"\bUSING\b",
)
@dataclass
class SqlExecutionResult:
sql: str
rows: List[Dict[str, Any]]
columns: List[str]
def _build_engine(settings: DbSettings) -> Engine:
connection_string = settings.connection_string()
uri = "mssql+pyodbc:///?odbc_connect=" + sa.engine.url.quote_plus(connection_string)
return sa.create_engine(uri, fast_executemany=True)
def _clean_sql(sql: str) -> str:
return sql.strip().rstrip(";")
def _contains_multiple_statements(sql: str) -> bool:
body = sql.rstrip()
if ";" not in body:
return False
# Allow a single trailing semicolon but forbid anything after it
last_semicolon = body.rfind(";")
trailing = body[last_semicolon + 1 :].strip()
return trailing != ""
def _enforce_top_clause(sql: str, max_rows: int) -> str:
pattern = re.compile(r"select\s+(distinct\s+)?", re.IGNORECASE)
leading_whitespace = len(sql) - len(sql.lstrip())
body = sql.lstrip()
match = pattern.match(body)
if not match:
return sql
# Detect existing TOP clause in the initial projection
leading_segment = body[: match.end() + 20].lower()
if "top" in leading_segment:
return sql
prefix = match.group(0)
remainder = body[match.end() :]
if match.group(1):
# prefix already includes "SELECT DISTINCT "
replacement = prefix + f"TOP ({max_rows}) " + remainder
else:
replacement = "SELECT TOP ({}) ".format(max_rows) + body[len("SELECT ") :]
return sql[:leading_whitespace] + replacement
def sanitize_sql(sql: str, max_rows: int = 500) -> str:
"""Ensure the SQL is safe to execute and apply a row limit."""
candidate = _clean_sql(sql)
if not candidate:
raise SqlValidationError("Generated SQL is empty.")
lowered = candidate.lstrip().lower()
if not lowered.startswith("select"):
raise SqlValidationError("Only SELECT statements are allowed.")
if _contains_multiple_statements(candidate):
raise SqlValidationError("Multiple statements detected; reject for safety.")
upper = candidate.upper()
for keyword in PROHIBITED_KEYWORDS:
if re.search(rf"\b{keyword}\b", upper):
raise SqlValidationError(f"Statement contains disallowed keyword: {keyword}")
for pattern in UNSUPPORTED_PATTERNS:
if re.search(pattern, candidate, flags=re.IGNORECASE):
raise SqlValidationError("Statement contains non-SQL Server syntax (e.g., ILIKE, NULLS LAST, LIMIT, OFFSET, USING).")
if max_rows <= 0:
raise SqlValidationError("max_rows must be greater than zero.")
limited = _enforce_top_clause(candidate, max_rows=max_rows)
return limited
def execute_sql(sql: str, max_rows: int = 500) -> SqlExecutionResult:
"""Validate and run the provided SQL against the configured MSSQL database."""
sanitized = sanitize_sql(sql, max_rows=max_rows)
settings = DbSettings.from_env()
engine = _build_engine(settings)
with engine.connect() as conn:
result = conn.execute(sa.text(sanitized))
columns = list(result.keys())
rows = [dict(row._mapping) for row in result]
return SqlExecutionResult(sql=sanitized, rows=rows, columns=columns)

View File

@@ -0,0 +1,35 @@
# SQL Agent Web UI
A lightweight FastAPI + vanilla JS frontend for interacting with the SugarScale SQL agent.
## Backend
Located at `db_agent/ui/backend/main.py`. It exposes:
- `POST /api/query` wraps the existing agent pipeline (LLM + optional SQL execution + logging).
- `GET /health` health probe.
- Serves the static frontend and index page.
### Run locally
```powershell
# Activate your virtual environment first
uvicorn db_agent.ui.backend.main:app --reload --host 0.0.0.0 --port 8000
```
The UI will be available at `http://localhost:8000/`. Adjust the host/port as needed.
## Frontend
Files under `db_agent/ui/frontend/`:
- `index.html` main page with the question form and results display.
- `static/app.js` handles form submission, fetches `/api/query`, renders results.
- `static/styles.css` modern styling.
## Configuration Notes
- The backend reuses environment variables (`DB_SERVER`, `DB_DATABASE`, etc.) for SQL execution, so ensure they are set before starting the FastAPI server.
- The backend expects the LLM endpoint configured in `db_agent/client.LlmConfig.base_url` (defaults to `http://192.168.0.30:8080`). Update if your TGI server runs elsewhere.
- Interaction logs still append to `db_agent/logs/query_log.jsonl` by default.
## Next Ideas
- Add user authentication or API keys.
- Save favorite queries or table presets.
- Stream results for large datasets.

View File

@@ -0,0 +1,181 @@
from __future__ import annotations
import logging
import json
from pathlib import Path
from typing import Literal, Optional
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
from db_agent.client import SqlAgentClient, default_client
from db_agent.log_utils import log_interaction
from db_agent.sql_executor import SqlExecutionResult, SqlValidationError, execute_sql
logger = logging.getLogger("db_agent_ui")
class QueryRequest(BaseModel):
question: str = Field(..., description="Natural language question")
tables: Optional[list[str]] = Field(default=None, description="Optional table hints")
execute: bool = Field(default=False, description="Run the generated SQL against MSSQL")
max_rows: int = Field(default=500, ge=1, description="Row cap applied via TOP clause")
feedback: Optional[str] = Field(default=None, description="Optional user feedback tag")
class QueryResponse(BaseModel):
sql: str
summary: str
sanitized_sql: Optional[str] = None
rows: Optional[list[dict[str, object]]] = None
columns: Optional[list[str]] = None
row_count: Optional[int] = None
llm_warning: Optional[str] = None
execution_status: Optional[str] = None
execution_error: Optional[str] = None
user_feedback: Optional[str] = None
app = FastAPI(title="SugarScale SQL Agent UI", version="0.1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
frontend_dir = Path(__file__).resolve().parent.parent / "frontend"
static_dir = frontend_dir / "static"
if static_dir.exists():
app.mount("/static", StaticFiles(directory=static_dir), name="static")
_agent_client: Optional[SqlAgentClient] = None
def get_client() -> SqlAgentClient:
global _agent_client
if _agent_client is None:
_agent_client = default_client()
return _agent_client
class FeedbackRequest(BaseModel):
question: str = Field(..., description="Question that produced the answer")
sql: str = Field(..., description="Generated SQL that was reviewed")
summary: Optional[str] = None
sanitized_sql: Optional[str] = None
feedback: Literal["correct", "incorrect"] = Field(..., description="User feedback tag")
@app.post("/api/query", response_model=QueryResponse)
def query_endpoint(payload: QueryRequest) -> QueryResponse:
client = get_client()
response = client.query(question=payload.question, table_hints=payload.tables)
sql = response.get("sql", "").strip()
summary = response.get("summary", "").strip()
warning = response.get("llm_warning")
raw_response = json.dumps(response, ensure_ascii=False)
sanitized_sql = None
rows = None
columns = None
row_count = None
execution_status = None
execution_error = None
normalized_sql = sql.lstrip()
has_sql = bool(normalized_sql)
sql_is_select = normalized_sql.lower().startswith("select") if has_sql else False
if payload.execute:
if not has_sql:
warning = warning or "Model did not return executable SQL; nothing was run."
elif not sql_is_select:
warning = warning or "Model did not return a valid SELECT statement; execution skipped."
else:
try:
exec_result: SqlExecutionResult = execute_sql(
normalized_sql,
max_rows=payload.max_rows,
)
except SqlValidationError as exc:
execution_error = str(exc)
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc: # pylint: disable=broad-except
logger.exception("SQL execution error")
execution_error = str(exc)
raise HTTPException(status_code=500, detail="SQL execution failed") from exc
else:
sanitized_sql = exec_result.sql
rows = exec_result.rows
columns = exec_result.columns
row_count = len(rows)
execution_status = "success"
log_interaction(
question=payload.question,
generated_sql=sql,
summary=summary,
sanitized_sql=sanitized_sql,
row_count=row_count,
execution_status=execution_status,
execution_error=execution_error,
raw_response=raw_response,
user_feedback=payload.feedback,
metadata={
"source": "ui",
"execute": payload.execute,
"tables": payload.tables,
"llm_warning": warning,
},
)
return QueryResponse(
sql=sql,
summary=summary,
sanitized_sql=sanitized_sql,
rows=rows,
columns=columns,
row_count=row_count,
llm_warning=warning,
execution_status=execution_status,
execution_error=execution_error,
user_feedback=payload.feedback,
)
@app.post("/api/feedback")
def record_feedback(payload: FeedbackRequest) -> dict[str, str]:
feedback_value = payload.feedback.lower()
log_interaction(
question=payload.question,
generated_sql=payload.sql,
summary=payload.summary or "",
sanitized_sql=payload.sanitized_sql,
row_count=None,
execution_status=None,
execution_error=None,
raw_response=None,
user_feedback=feedback_value,
metadata={
"source": "ui-feedback",
"feedback_only": True,
},
)
return {"status": "recorded"}
@app.get("/health")
def healthcheck() -> dict[str, str]:
return {"status": "ok"}
@app.get("/")
def index() -> FileResponse:
return FileResponse(frontend_dir / "index.html")

View File

@@ -0,0 +1,75 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>SugarScale SQL Agent</title>
<link rel="stylesheet" href="/static/styles.css" />
</head>
<body>
<header>
<h1>SugarScale SQL Agent</h1>
<p>Ask natural-language questions and optionally execute the generated SQL.</p>
</header>
<main>
<section class="panel">
<form id="query-form">
<label for="question">Question</label>
<textarea id="question" name="question" rows="3" placeholder="e.g., How many loads were completed yesterday?" required></textarea>
<label for="tables">Table hints (comma-separated)</label>
<input id="tables" name="tables" type="text" placeholder="dbo.SugarLoadData" />
<div class="options">
<label>
<input type="checkbox" id="execute" name="execute" /> Execute SQL
</label>
<label for="max-rows">Max rows</label>
<input id="max-rows" name="max_rows" type="number" min="1" value="500" />
</div>
<button type="submit">Run</button>
</form>
</section>
<section class="panel" id="results" hidden>
<h2>Results</h2>
<div class="warning" id="warning" hidden></div>
<div id="summary"></div>
<details>
<summary>Generated SQL</summary>
<pre><code id="generated-sql"></code></pre>
</details>
<details id="sanitized-block" hidden>
<summary>Sanitized SQL (executed)</summary>
<pre><code id="sanitized-sql"></code></pre>
</details>
<div id="row-count"></div>
<table id="result-table" hidden>
<thead id="result-thead"></thead>
<tbody id="result-tbody"></tbody>
</table>
<div id="feedback-panel" hidden>
<h3>Was this answer helpful?</h3>
<div class="feedback-actions">
<button type="button" id="feedback-correct">Mark Correct</button>
<button type="button" id="feedback-incorrect" class="secondary">Needs Work</button>
</div>
<p id="feedback-status" hidden></p>
</div>
</section>
<section class="panel error" id="error" hidden>
<h2>Error</h2>
<pre id="error-message"></pre>
</section>
</main>
<footer>
<small>Powered by the SugarScale SQL agent.</small>
</footer>
<script src="/static/app.js" type="module"></script>
</body>
</html>

View File

@@ -0,0 +1,182 @@
const form = document.getElementById("query-form");
const resultsPanel = document.getElementById("results");
const errorPanel = document.getElementById("error");
const warningEl = document.getElementById("warning");
const summaryEl = document.getElementById("summary");
const generatedSqlEl = document.getElementById("generated-sql");
const sanitizedBlock = document.getElementById("sanitized-block");
const sanitizedSqlEl = document.getElementById("sanitized-sql");
const rowCountEl = document.getElementById("row-count");
const tableEl = document.getElementById("result-table");
const tableHeadEl = document.getElementById("result-thead");
const tableBodyEl = document.getElementById("result-tbody");
const errorMessageEl = document.getElementById("error-message");
const feedbackPanel = document.getElementById("feedback-panel");
const feedbackCorrectBtn = document.getElementById("feedback-correct");
const feedbackIncorrectBtn = document.getElementById("feedback-incorrect");
const feedbackStatus = document.getElementById("feedback-status");
let latestResult = null;
function resetPanels() {
resultsPanel.hidden = true;
errorPanel.hidden = true;
warningEl.hidden = true;
warningEl.textContent = "";
summaryEl.textContent = "";
generatedSqlEl.textContent = "";
sanitizedBlock.hidden = true;
sanitizedSqlEl.textContent = "";
rowCountEl.textContent = "";
tableEl.hidden = true;
tableHeadEl.innerHTML = "";
tableBodyEl.innerHTML = "";
errorMessageEl.textContent = "";
feedbackPanel.hidden = true;
feedbackStatus.hidden = true;
feedbackStatus.textContent = "";
latestResult = null;
}
function renderTable(columns, rows) {
if (!columns || !rows || rows.length === 0) {
tableEl.hidden = true;
return;
}
const headerRow = document.createElement("tr");
columns.forEach((col) => {
const th = document.createElement("th");
th.textContent = col;
headerRow.appendChild(th);
});
tableHeadEl.appendChild(headerRow);
rows.forEach((row) => {
const tr = document.createElement("tr");
columns.forEach((col) => {
const td = document.createElement("td");
const value = row[col];
td.textContent = value === null || value === undefined ? "" : String(value);
tr.appendChild(td);
});
tableBodyEl.appendChild(tr);
});
tableEl.hidden = false;
}
form.addEventListener("submit", async (event) => {
event.preventDefault();
resetPanels();
const question = document.getElementById("question").value.trim();
const tablesValue = document.getElementById("tables").value.trim();
const execute = document.getElementById("execute").checked;
const maxRows = parseInt(document.getElementById("max-rows").value, 10) || 500;
if (!question) {
errorPanel.hidden = false;
errorMessageEl.textContent = "Please enter a question.";
return;
}
const payload = {
question,
tables: tablesValue ? tablesValue.split(",").map((s) => s.trim()).filter(Boolean) : undefined,
execute,
max_rows: maxRows,
feedback: null,
};
try {
const response = await fetch("/api/query", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || `Request failed with status ${response.status}`);
}
const data = await response.json();
summaryEl.textContent = data.summary || "(No summary provided)";
generatedSqlEl.textContent = data.sql || "";
if (data.llm_warning) {
warningEl.textContent = data.llm_warning;
warningEl.hidden = false;
}
if (data.sanitized_sql) {
sanitizedSqlEl.textContent = data.sanitized_sql;
sanitizedBlock.hidden = false;
}
if (typeof data.row_count === "number") {
rowCountEl.textContent = `Rows returned: ${data.row_count}`;
}
renderTable(data.columns, data.rows);
latestResult = {
question,
sql: data.sql || "",
summary: data.summary || "",
sanitized_sql: data.sanitized_sql || null,
};
feedbackPanel.hidden = false;
feedbackStatus.hidden = true;
feedbackStatus.textContent = "";
resultsPanel.hidden = false;
} catch (error) {
errorPanel.hidden = false;
errorMessageEl.textContent = error.message || String(error);
}
});
async function sendFeedback(tag) {
if (!latestResult) {
return;
}
const payload = {
question: latestResult.question,
sql: latestResult.sql,
summary: latestResult.summary,
sanitized_sql: latestResult.sanitized_sql,
feedback: tag,
};
feedbackStatus.hidden = false;
feedbackStatus.textContent = "Sending feedback...";
feedbackCorrectBtn.disabled = true;
feedbackIncorrectBtn.disabled = true;
try {
const response = await fetch("/api/feedback", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || `Feedback request failed with status ${response.status}`);
}
feedbackStatus.textContent = tag === "correct" ? "Marked as correct." : "Marked as needs work.";
} catch (error) {
feedbackStatus.textContent = error.message || String(error);
} finally {
feedbackCorrectBtn.disabled = false;
feedbackIncorrectBtn.disabled = false;
}
}
feedbackCorrectBtn.addEventListener("click", () => sendFeedback("correct"));
feedbackIncorrectBtn.addEventListener("click", () => sendFeedback("incorrect"));

View File

@@ -0,0 +1,144 @@
* {
box-sizing: border-box;
}
body {
font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
margin: 0;
padding: 0;
background: #f4f6f8;
color: #0f172a;
}
header,
footer {
background: #0f172a;
color: #f8fafc;
padding: 1.5rem;
text-align: center;
}
main {
max-width: 960px;
margin: 2rem auto;
display: grid;
gap: 1.5rem;
}
.panel {
background: #ffffff;
padding: 1.5rem;
border-radius: 12px;
box-shadow: 0 12px 24px rgba(15, 23, 42, 0.08);
}
.panel.error {
border-left: 6px solid #ef4444;
}
.warning {
background: #fef3c7;
color: #92400e;
border-left: 4px solid #f59e0b;
padding: 0.75rem 1rem;
border-radius: 8px;
margin-bottom: 1rem;
white-space: pre-wrap;
}
label {
display: block;
font-weight: 600;
margin-bottom: 0.35rem;
}
textarea,
input,
button {
width: 100%;
padding: 0.75rem;
border-radius: 8px;
border: 1px solid #cbd5f5;
font-size: 1rem;
margin-bottom: 1rem;
}
textarea:focus,
input:focus {
outline: none;
border-color: #2563eb;
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.2);
}
.options {
display: flex;
gap: 1rem;
align-items: center;
}
.options label {
margin-bottom: 0;
font-weight: 500;
}
button {
background: linear-gradient(135deg, #2563eb, #1d4ed8);
color: #fff;
border: none;
cursor: pointer;
font-weight: 600;
transition: transform 0.15s ease, box-shadow 0.15s ease;
}
button:hover {
transform: translateY(-1px);
box-shadow: 0 10px 20px rgba(37, 99, 235, 0.25);
}
button.secondary {
background: linear-gradient(135deg, #64748b, #475569);
}
pre {
background: #0f172a;
color: #e2e8f0;
padding: 1rem;
border-radius: 8px;
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 1rem;
}
th,
td {
border: 1px solid #e2e8f0;
padding: 0.65rem;
text-align: left;
}
th {
background: #f1f5f9;
}
#error-message {
white-space: pre-wrap;
}
#feedback-panel {
margin-top: 1.5rem;
}
.feedback-actions {
display: flex;
gap: 1rem;
margin-bottom: 0.75rem;
}
#feedback-status {
color: #0369a1;
font-weight: 600;
}

View File

@@ -0,0 +1,70 @@
# Database Agent Toolkit
This folder hosts utilities and documentation for the natural-language SQL agent.
## Folders
- `extractor/`: Python tooling to pull schema metadata from the MSSQL sandbox.
- `prompting/`: Prompt builders that merge curated context into LLM requests.
- `context/`: Generated artifacts (schema JSON, glossary, examples) injected into LLM prompts.
- `deployment/`: Docker Compose for hosting open-source SQL models via TGI.
- `sql_executor.py`: Validation + execution helpers for running generated SQL safely.
- `log_utils.py`: JSONL logging utilities for question/SQL traces.
- `ui/`: FastAPI backend and static frontend for a simple web interface.
- `knowledge_prep.md`: Checklist for curating high-quality agent context.
## Python Setup
1. **Install dependencies** (create a venv if needed):
```powershell
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install -r requirements.txt
pip install -r db_agent/requirements.txt
```
Ensure the Microsoft ODBC driver (17 or 18) is installed on the machine.
2. **Configure environment variables** (never commit credentials):
```powershell
# Dot-source so values remain in the current shell
. .\db_agent\scripts\Set-DbEnv.ps1 -Server "SUGARSCALE\SQLEXPRESS" -Database "SugarScale_Lasuca" -Username "SugarAI"
```
The script prompts for the password (or accept `-Password (Read-Host -AsSecureString)`) and exports `DB_SERVER`, `DB_DATABASE`, `DB_USERNAME`, `DB_PASSWORD`, `DB_DRIVER` (default `ODBC Driver 17 for SQL Server`), `DB_ENCRYPT`, and `DB_TRUST_CERT`. Override any parameter via the corresponding flag.
3. **Run the schema extraction job**:
```powershell
python -m db_agent.extractor --job schema --schema dbo --output db_agent/context/schema.json
```
- `--schema`: restricts the crawl to a specific SQL schema (omit to capture all).
- `--output`: where to write the structured schema document consumed by the agent.
4. **Review the output** under `db_agent/context/` and commit sanitized artifacts alongside code when appropriate.
## Running the SQL Agent
1. Ensure the TGI container in `deployment/docker-compose.yml` is running (default endpoint `http://192.168.0.30:8080`).
2. Execute a question against the model:
```powershell
python -m db_agent.run_agent "How many loads were completed yesterday?" --tables dbo.SugarLoadData
```
The script prints JSON with `sql` and `summary` fields.
3. Use `--execute` to run the validated SQL against MSSQL (enforced `TOP` limit via `--max-rows`, default `500`):
```powershell
python -m db_agent.run_agent "Top gross loads this week" --tables dbo.SugarLoadData --execute --max-rows 200
```
Preview rows (up to 5) and the sanitized SQL are echoed to stdout.
4. Interactions are logged to `db_agent/logs/query_log.jsonl` by default; override with `--log-path` or disable logging via `--no-log`.
5. To point at a different inference endpoint, edit `LlmConfig.base_url` in `db_agent/client.py` (the client posts to `<base_url>/generate`).
## Web UI
1. Install the web dependencies (already in `db_agent/requirements.txt`).
2. Start the FastAPI server:
```powershell
uvicorn db_agent.ui.backend.main:app --reload --host 0.0.0.0 --port 8000
```
3. Open `http://localhost:8000/` to access the UI. Submit questions, optionally run SQL, and view results/preview tables.
4. Environment variables for MSSQL access must be set in the shell before launching the server.
## Next Steps
- Add additional extractor jobs (lookup value snapshots, glossary builders) following the same pattern as `schema_snapshot.py`.
- Integrate the extractor into CI/CD or a scheduled task to keep the agent context fresh.
- Use `knowledge_prep.md` as a guide when enriching the context files with human-curated insights.
- Extend `db_agent/client.py` with SQL validation/execution layers and logging of user questions vs. generated queries.
- Consider adding automated SQL result validation (e.g., schema assertions) before surfacing answers to end users.

View File

@@ -0,0 +1,15 @@
"""Tools for building and running the SugarScale SQL agent."""
from .client import SqlAgentClient, default_client
from .prompting import AgentContext, build_prompt, load_context
from .sql_executor import execute_sql, sanitize_sql
__all__ = [
"SqlAgentClient",
"default_client",
"AgentContext",
"build_prompt",
"load_context",
"execute_sql",
"sanitize_sql",
]

Binary file not shown.

View File

@@ -0,0 +1,367 @@
"""Client utilities for calling the local TGI-hosted SQL model."""
from __future__ import annotations
import json
import logging
import re
from dataclasses import dataclass
from typing import Any, Dict, Optional
import requests
from .prompting import AgentContext, build_prompt, load_context
logger = logging.getLogger(__name__)
@dataclass
class LlmConfig:
base_url: str = "http://192.168.0.30:8080"
model: str = "defog/sqlcoder-7b-2"
temperature: float = 0.1
max_new_tokens: Optional[int] = 512
class SqlAgentClient:
"""Wrapper that builds prompts and fetches SQL from the LLM service."""
_FORMAT_REMINDER = (
"Reminder: Respond with valid JSON exactly as {\"sql\": \"<single T-SQL SELECT statement>\", "
"\"summary\": \"<one sentence summary>\"}. The sql value must start with SELECT, contain only one "
"statement, use SQL Server syntax (e.g., LIKE instead of ILIKE, ORDER BY without NULLS LAST/FIRST), and "
"avoid fabricated literals or extra filters. Only add WHERE conditions or time windows that the user explicitly mentioned. If clarification is required, set sql to an empty string and explain why in summary."
)
def __init__(self, context: AgentContext, llm_config: Optional[LlmConfig] = None) -> None:
self.context = context
self.config = llm_config or LlmConfig()
def build_request_payload(
self,
question: str,
table_hints: Optional[list[str]] = None,
*,
format_hint: Optional[str] = None,
) -> Dict[str, Any]:
prompt = build_prompt(
question=question,
context=self.context,
table_hints=table_hints,
format_hint=format_hint,
)
parameters: Dict[str, Any] = {
"temperature": max(self.config.temperature, 1e-5),
"return_full_text": False,
}
if self.config.max_new_tokens is not None:
parameters["max_new_tokens"] = self.config.max_new_tokens
return {
"inputs": prompt,
"parameters": parameters,
}
def query(self, question: str, table_hints: Optional[list[str]] = None) -> Dict[str, Any]:
warnings: list[str] = []
question_allows_timeframe = self._question_mentions_timeframe(question)
parsed: Optional[Dict[str, Any]] = None
for attempt in range(2):
if attempt == 1:
format_hint = (
self._FORMAT_REMINDER
+ f' The user question is: "{question}". Do not add filters beyond what is explicitly stated.'
)
else:
format_hint = None
payload = self.build_request_payload(question, table_hints, format_hint=format_hint)
parsed = self._invoke_generate(payload)
sql_text = parsed.get("sql", "") if isinstance(parsed, dict) else ""
normalized_sql = self._normalize_sql(sql_text) if sql_text else ""
parsed["sql"] = normalized_sql
if normalized_sql and not question_allows_timeframe:
normalized_sql, stripped_temporal = self._strip_unrequested_temporal_filters(normalized_sql)
if stripped_temporal:
parsed["sql"] = normalized_sql
warnings.append("Postprocess: Removed unrequested date/time filters from SQL output.")
if normalized_sql:
normalized_sql, stripped_compat = self._replace_non_sqlserver_syntax(normalized_sql)
if stripped_compat:
parsed["sql"] = normalized_sql
warnings.append("Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).")
if normalized_sql and normalized_sql.lstrip().lower().startswith("select"):
if warnings:
parsed["llm_warning"] = "; ".join(warnings)
return parsed
warning_message = parsed.get("llm_warning")
if not warning_message:
warning_message = "Model response did not include a valid SELECT statement."
# Capture repeated addition of unrequested filters for auditing
sql_text = parsed.get("sql", "")
if sql_text:
lowered_sql = sql_text.lower()
if any(phrase in lowered_sql for phrase in ("last 24", "last24", "24 hour", "24-hour")):
warning_message = (
"Model added an unrequested time filter. Ensure future responses only add filters present in the question."
)
warnings.append(f"Attempt {attempt + 1}: {warning_message}")
if attempt == 0:
logger.info("Retrying LLM request with explicit formatting reminder.")
continue
# Second attempt also failed
warnings.append("Attempt 2: Second attempt also failed to produce a valid SELECT statement.")
parsed["llm_warning"] = "; ".join(warnings)
return parsed
# Should not reach here, but provide a safe fallback
if parsed:
parsed.setdefault("sql", "")
parsed.setdefault("summary", "")
parsed["llm_warning"] = "; ".join(warnings) if warnings else "LLM did not produce a usable response."
return parsed
return {
"sql": "",
"summary": "",
"llm_warning": "LLM did not produce a usable response.",
}
def _invoke_generate(self, payload: Dict[str, Any]) -> Dict[str, Any]:
headers = {"Content-Type": "application/json"}
response = requests.post(
f"{self.config.base_url}/generate",
headers=headers,
data=json.dumps(payload),
timeout=120,
)
response.raise_for_status()
try:
data = response.json()
except ValueError:
body = response.text.strip()
return self._fallback_response(
raw=body,
message="LLM HTTP response was not JSON; returning raw text.",
)
content = data.get("generated_text") if isinstance(data, dict) else None
if not content:
raw = response.text.strip()
return self._fallback_response(
raw=raw or str(data),
message="LLM response missing generated_text field; returning raw text.",
)
return self._parse_response(content)
@staticmethod
def _strip_code_fence(text: str) -> str:
stripped = text.strip()
if stripped.startswith("```") and stripped.endswith("```"):
without_ticks = stripped.strip("`")
parts = without_ticks.split("\n", 1)
if len(parts) == 2:
body = parts[1]
else:
body = parts[0]
return body.rsplit("```", 1)[0] if "```" in body else body
return stripped
def _parse_response(self, content: str) -> Dict[str, Any]:
"""Attempt to decode JSON, handling common formatting wrappers."""
raw = content.strip()
candidates = [raw]
candidates.append(self._strip_code_fence(raw))
# Extract substring between first and last braces if needed
start = raw.find("{")
end = raw.rfind("}")
if start != -1 and end != -1 and end > start:
candidates.append(raw[start : end + 1])
for candidate in candidates:
candidate = candidate.strip()
if not candidate:
continue
try:
return json.loads(candidate)
except json.JSONDecodeError:
continue
# Heuristic: parse patterns like "SQL query: ... Summary: ..."
lower = raw.lower()
if "sql query:" in lower:
sql_start = lower.find("sql query:") + len("sql query:")
summary_start = lower.find("summary:")
if summary_start != -1:
sql_text = raw[sql_start:summary_start].strip()
summary_text = raw[summary_start + len("summary:") :].strip()
return {"sql": sql_text, "summary": summary_text}
if lower.startswith("sql:"):
sql_text = raw.split(":", 1)[1].strip()
return {"sql": sql_text, "summary": ""}
# Handle outputs like "... Summary: ..." (with or without explicit SQL label)
summary_idx = lower.rfind("summary:")
if summary_idx != -1:
sql_section = raw[:summary_idx].strip()
summary_text = raw[summary_idx + len("summary:") :].strip()
# Remove wrapping quotes if present
if summary_text.startswith("\"") and summary_text.endswith("\""):
summary_text = summary_text[1:-1]
if sql_section.lower().startswith("sql generated:"):
sql_section = sql_section[len("sql generated:") :].strip()
return {"sql": sql_section, "summary": summary_text}
# Final fallback: treat entire content as SQL and leave summary blank.
if raw.upper().startswith("SELECT") or "SELECT" in raw.upper():
return {"sql": raw.strip(), "summary": ""}
return self._fallback_response(
raw=raw,
message="LLM output could not be parsed; returning raw text.",
)
@staticmethod
def _fallback_response(raw: str, message: str) -> Dict[str, Any]:
preview = raw[:200] if raw else "(empty response)"
logger.warning("%s preview=%s", message, preview)
return {
"sql": "",
"summary": raw,
"llm_warning": f"{message} Preview: {preview}",
}
@staticmethod
def _question_mentions_timeframe(question: str) -> bool:
lowered = question.lower()
if re.search(
r"\b(today|yesterday|tonight|this|current|previous|prior|recent|last|past|since|ago|between|before|after|during)\b",
lowered,
):
return True
if re.search(
r"\b(day|days|week|weeks|month|months|quarter|quarters|year|years|hour|hours|minute|minutes)\b",
lowered,
):
return True
if re.search(r"\b(january|february|march|april|may|june|july|august|september|october|november|december)\b", lowered):
return True
if re.search(r"\b(mon|tue|wed|thu|fri|sat|sun)(day)?\b", lowered):
return True
if re.search(r"\b20\d{2}\b", lowered):
return True
return False
@staticmethod
def _strip_unrequested_temporal_filters(sql: str) -> tuple[str, bool]:
candidate = sql
temporal_regex = r"(DATEADD|DATEDIFF|DATEPART|SYSDATETIME|GETDATE|CURRENT_TIMESTAMP)"
changed = False
clause_pattern = re.compile(
rf"\s+(AND|OR)\s+[^;]*?{temporal_regex}[^;]*?(?=(\bAND\b|\bOR\b|\bGROUP BY\b|\bORDER BY\b|\bHAVING\b|$))",
re.IGNORECASE | re.DOTALL,
)
candidate, replaced = clause_pattern.subn("", candidate)
if replaced:
changed = True
where_pattern = re.compile(
rf"\bWHERE\b\s+[^;]*?{temporal_regex}[^;]*?(?=(\bGROUP BY\b|\bORDER BY\b|\bHAVING\b|$))",
re.IGNORECASE | re.DOTALL,
)
candidate, replaced = where_pattern.subn("", candidate)
if replaced:
changed = True
dangling_where_pattern = re.compile(r"\bWHERE\b\s*(?=(GROUP BY|ORDER BY|HAVING|$))", re.IGNORECASE)
candidate, replaced = dangling_where_pattern.subn("", candidate)
if replaced:
changed = True
if changed:
candidate = re.sub(r"\s{2,}", " ", candidate)
candidate = re.sub(r"\s+(GROUP BY|ORDER BY|HAVING)\b", r" \1", candidate, flags=re.IGNORECASE)
candidate = re.sub(r"\s+;", ";", candidate)
return candidate.strip(), changed
@staticmethod
def _normalize_sql(sql_text: str) -> str:
text = sql_text.strip()
# Remove markdown fences if still present
if text.startswith("```") and text.endswith("```"):
inner = text.strip("`")
parts = inner.split("\n", 1)
text = parts[1] if len(parts) == 2 else parts[0]
text = text.rsplit("```", 1)[0]
prefix_pattern = re.compile(r"^[\s\.\?\-:\*•]*sql(?:\s+(?:query|statement))?\s*:\s*", re.IGNORECASE)
text = prefix_pattern.sub("", text, count=1)
alt_prefix_pattern = re.compile(r"^[\s\.\?\-:\*•]*(?:generated sql|query|answer)\s*:\s*", re.IGNORECASE)
text = alt_prefix_pattern.sub("", text, count=1)
# Drop leading punctuation or bullet artifacts before the SELECT keyword
lowered = text.lower()
select_idx = lowered.find("select")
if select_idx > 0:
leading = text[:select_idx]
if leading.strip(" \n\t\r:-*•?.") == "":
text = text[select_idx:]
# Remove any trailing summary section that may still be attached
summary_split = re.split(r"(?i)\bsummary\s*:", text, maxsplit=1)
if summary_split:
text = summary_split[0]
return text.strip()
@staticmethod
def _replace_non_sqlserver_syntax(sql_text: str) -> tuple[str, bool]:
changed = False
sql = sql_text
# Replace ILIKE with LIKE + UPPER for case-insensitive matching
def replace_ilike(match: re.Match[str]) -> str:
nonlocal changed
column = match.group("column")
value = match.group("value")
if column.startswith('"') and column.endswith('"'):
column = f"[{column[1:-1]}]"
if value.startswith('"') and value.endswith('"'):
value = f"'{value[1:-1]}'"
changed = True
return f"UPPER({column}) LIKE UPPER({value})"
ilike_pattern = re.compile(
r"(?P<column>(?:[\w\.\[\]]+|\"[^\"]+\"))\s+ILIKE\s+(?P<value>'[^']*'|\"[^\"]*\"|:[\w_]+)",
re.IGNORECASE,
)
sql = ilike_pattern.sub(replace_ilike, sql)
# Remove NULLS FIRST/LAST clauses
nulls_pattern = re.compile(r"\s+NULLS\s+(?:FIRST|LAST)", re.IGNORECASE)
if nulls_pattern.search(sql):
sql = nulls_pattern.sub("", sql)
changed = True
return sql.strip(), changed
def default_client() -> SqlAgentClient:
context = load_context()
config = LlmConfig()
return SqlAgentClient(context=context, llm_config=config)

View File

@@ -0,0 +1,27 @@
[
{
"question": "How many loads were completed yesterday?",
"sql": "SELECT COUNT(*) AS load_count\nFROM dbo.SugarLoadData\nWHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);",
"notes": "Uses DateOut to ensure the truck exited; bounds the window on the local date."
},
{
"question": "Show the top 5 heaviest loads in the past week.",
"sql": "SELECT TOP (5) SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\nFROM dbo.SugarLoadData\nWHERE DateOut >= DATEADD(day, -7, SYSDATETIME())\nORDER BY GrossWt DESC;",
"notes": "Ranks by gross weight; includes net/tare columns for context."
},
{
"question": "List average payload tons per hauling company for the last 30 days.",
"sql": "SELECT TCompanyName, AVG(Tons) AS avg_tons, COUNT(*) AS load_count\nFROM dbo.SugarLoadData\nWHERE DateOut >= DATEADD(day, -30, SYSDATETIME())\n AND Tons IS NOT NULL\nGROUP BY TCompanyName\nORDER BY avg_tons DESC;",
"notes": "Filters out null payloads and groups by company for business comparison."
},
{
"question": "Which vehicles have missing tare weights on recent loads?",
"sql": "SELECT VehicleId_Fk, COUNT(*) AS missing_tare_count\nFROM dbo.SugarLoadData\nWHERE DateOut >= DATEADD(day, -14, SYSDATETIME())\n AND (TareWt IS NULL OR TareWt = 0)\nGROUP BY VehicleId_Fk\nORDER BY missing_tare_count DESC;",
"notes": "Helps operations schedule tare recalibration."
},
{
"question": "Provide hourly load counts for the current day.",
"sql": "SELECT DATEPART(hour, DateOut) AS hour_of_day, COUNT(*) AS loads\nFROM dbo.SugarLoadData\nWHERE DateOut >= CAST(SYSDATETIME() AS date)\nGROUP BY DATEPART(hour, DateOut)\nORDER BY hour_of_day;",
"notes": "Generates time-series data for real-time dashboards; assumes DateOut in local timezone."
}
]

View File

@@ -0,0 +1,44 @@
# SugarScale MSSQL Glossary
Use this glossary to translate operator language into database columns for the SQL agent.
## Core Tables
- **dbo.SugarLoadData**: Per-load grain deliveries recorded at the truck scale. Each row represents a truck entering/exiting the facility with weight measurements and logistics metadata.
- **dbo.SugarVehicles**: Reference table for registered trucks/trailers and their default properties (company, RFID tag, tare weight).
- **dbo.SugarParams**: System parameters; currently stores a single `StartTime` indicating when the scale captured data begins.
## Common Terms
- **Load** → `dbo.SugarLoadData`
- `SugarLoadID_Pk`: Unique identifier for a scale transaction (primary key).
- `VehicleId_Fk`: Truck or vehicle identifier referencing `dbo.SugarVehicles.VehicleId_Pk`.
- `TrailerTypeID`: Trailer classification (e.g., hopper, dump). Stored as free text; standardize before analytics when possible.
- `TCompanyName`: Hauling company name as captured at the kiosk.
- `DriverID`: Driver badge or license; alphanumeric string up to 500 chars.
- `LoadingLocation`: Where the load originated (hopper, wh1, wh2, etc.).
- `Destination`: Planned delivery point or storage yard.
- `DateIn`: Timestamp when the vehicle weighed in (in local plant timezone).
- `DateOut`: Timestamp when the vehicle weighed out or exited.
- `ScaleWT`: Raw indicator from the scale prior to adjustments (integer pounds).
- `GrossWt`: Gross weight measured on exit, in pounds.
- `TareIN`: Tare weight observed on entry (empty truck), in pounds.
- `TareWt`: Tare weight applied for net calculations; may be sourced from default or reweigh.
- `Tons`: Net payload in short tons (calculated from gross-tare).
- `LoadType`: Category flag (e.g., sugar, molasses). Align with scheduling terminology.
- `Alt_Barcode_Scan`: Secondary barcode capture used for redundancy; 50-character limit.
- **Vehicle** → `dbo.SugarVehicles`
- `VehicleId_Pk`: Unique truck identifier (matches `VehicleId_Fk`).
- `TCompanyName`: Default operator/contractor name for the vehicle record.
- `RFID`: RFID tag assigned to the truck for automatic gate reads.
- `Tare`: Stored tare weight (decimal, pounds). Use when `SugarLoadData.TareWt` is null.
- `LastTareTime`: Timestamp of the last verified tare measurement.
- `DefaultDest`: Common destination code used to prefill load forms.
- **System Start** → `dbo.SugarParams.StartTime`
- Indicates the earliest reliable timestamp in the SugarLoadData feed; use when bounding historical reports.
## Business Notes
- Weight fields are stored in pounds except `Tons`, which is short tons (`lbs / 2000`). Convert before aggregating if downstream systems expect metric tons.
- `DateIn` and `DateOut` are expected to be in local plant time without timezone metadata; adjust to UTC when integrating with other systems.
- Null `VehicleId_Fk` rows usually indicate walk-on loads or manual overrides; treat carefully when joining to `SugarVehicles`.
- `LoadType` and `TrailerTypeID` are free text and may have inconsistent casing; normalize to upper case when filtering.

View File

@@ -0,0 +1,186 @@
{
"tables": {
"dbo.SugarLoadData": {
"columns": [
{
"default": null,
"max_length": 255,
"name": "SugarLoadID_Pk",
"nullable": false,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "VehicleId_Fk",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "TrailerTypeID",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "TCompanyName",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 500,
"name": "DriverID",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "LoadingLocation",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "Destination",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": null,
"name": "DateIn",
"nullable": true,
"type": "datetime"
},
{
"default": null,
"max_length": null,
"name": "DateOut",
"nullable": true,
"type": "datetime"
},
{
"default": null,
"max_length": null,
"name": "ScaleWT",
"nullable": true,
"type": "int"
},
{
"default": null,
"max_length": null,
"name": "GrossWt",
"nullable": true,
"type": "float"
},
{
"default": null,
"max_length": null,
"name": "TareIN",
"nullable": true,
"type": "float"
},
{
"default": null,
"max_length": null,
"name": "TareWt",
"nullable": true,
"type": "float"
},
{
"default": null,
"max_length": null,
"name": "Tons",
"nullable": true,
"type": "float"
},
{
"default": null,
"max_length": 255,
"name": "LoadType",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 50,
"name": "Alt_Barcode_Scan",
"nullable": true,
"type": "nvarchar"
}
],
"name": "SugarLoadData",
"relationships": [],
"schema": "dbo"
},
"dbo.SugarParams": {
"columns": [
{
"default": null,
"max_length": null,
"name": "StartTime",
"nullable": false,
"type": "datetime"
}
],
"name": "SugarParams",
"relationships": [],
"schema": "dbo"
},
"dbo.SugarVehicles": {
"columns": [
{
"default": null,
"max_length": 255,
"name": "VehicleId_Pk",
"nullable": false,
"type": "nvarchar"
},
{
"default": null,
"max_length": 255,
"name": "TCompanyName",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": 150,
"name": "RFID",
"nullable": true,
"type": "nvarchar"
},
{
"default": null,
"max_length": null,
"name": "Tare",
"nullable": true,
"type": "decimal"
},
{
"default": null,
"max_length": null,
"name": "LastTareTime",
"nullable": true,
"type": "datetime"
},
{
"default": null,
"max_length": 50,
"name": "DefaultDest",
"nullable": true,
"type": "nvarchar"
}
],
"name": "SugarVehicles",
"relationships": [],
"schema": "dbo"
}
}
}

View File

@@ -0,0 +1,76 @@
# Enum hints and typical ranges sourced from the SugarScale MSSQL sandbox.
# Update these after running profiling queries to keep the agent grounded.
columns:
dbo.SugarLoadData.LoadType:
values:
- Sugar
- Molases
notes: "Free-text field; normalize casing before comparisons."
dbo.SugarLoadData.TrailerTypeID:
values:
- Dump
notes: "Derived from manual entry; expect misspellings such as 'hopper' or 'Dump Trailer'."
dbo.SugarLoadData.LoadingLocation:
values:
- Hopper
- WH1
- WH2
- WH3
- BB
notes: "Locations map to historian area tags; keep a lookup table in sync with operations."
dbo.SugarLoadData.Destination:
values:
- Baldwin 3
- CSC
- BB
- Railcar
- LSR
- WH1
- WH2
- Barge
- Caldwell
- Other
notes: "Destination names align with production reporting dashboards; treat nulls as 'Unassigned'."
dbo.SugarLoadData.TCompanyName:
values:
- AOA
- JJAG,LLC
- Michael Durand
- Atchafalaya Seafood
- CSC
- Southern Prestige ENT
- LACA
- RALPH CALLIER
- ASR
- 14-1
- BIGDAWG
- Lasuca
- Earl Pania
- J Bradley
notes: "Company names align with production reporting dashboards; treat nulls as 'Unassigned'."
ranges:
dbo.SugarLoadData.GrossWt:
units: pounds
typical_min: 20000
typical_max: 95000
notes: "Scale enforces 40-ton cap; values above 90000 suggest sensor error."
dbo.SugarLoadData.TareWt:
units: pounds
typical_min: 20000
typical_max: 45000
notes: "Use stored vehicle tare when this column is null; sudden drops >20% flag for review."
dbo.SugarLoadData.Tons:
units: short_tons
typical_min: 5
typical_max: 40
notes: "Calculated payload; negative values indicate data entry mistakes."
confidence_flags:
dbo.SugarLoadData.VehicleId_Fk:
null_meaning: "Manual override or unregistered vehicle"
mitigation: "Join to SugarVehicles only after filtering nulls or alias to 'UNKNOWN_VEHICLE'."
dbo.SugarLoadData.DateOut:
null_meaning: "Truck has not exited; treat as active load."
mitigation: "Filter out null DateOut when reporting completed deliveries."

View File

@@ -0,0 +1,33 @@
# Local TGI Deployment for SQLCoder
This docker compose file runs Hugging Face Text Generation Inference (TGI) serving the `defog/sqlcoder-7b-2` model.
## Prerequisites
- NVIDIA GPU with recent drivers and CUDA runtime that matches the `nvidia-container-toolkit` installation.
- Docker and `docker compose` v2.
- Hugging Face access token with model download permissions (`HUGGING_FACE_HUB_TOKEN`).
## Usage
1. Export your Hugging Face token in the shell where you run compose:
```powershell
$env:HUGGING_FACE_HUB_TOKEN = "hf_..."
```
2. Launch the stack:
```powershell
docker compose -f db_agent/deployment/docker-compose.yml up -d
```
3. Check logs:
```powershell
docker compose -f db_agent/deployment/docker-compose.yml logs -f
```
4. The TGI OpenAI-compatible endpoint will be available at `http://localhost:8080/v1`. Use it with `openai`-compatible SDKs or direct HTTP calls.
## Notes
- The compose file pins `CUDA_VISIBLE_DEVICES=2` to target the 24 GB RTX 3090; update if your GPU indices differ.
- Token limits are tightened (`--max-total-tokens=3072`, `--max-input-length=2048`) to stay within 1624 GB cards.
- Models are cached on the `model-cache` volume to avoid re-downloading.
- To shut down:
```powershell
docker compose -f db_agent/deployment/docker-compose.yml down
```
- For CPU-only testing, remove the `deploy.resources` block and expect very slow inference.

View File

@@ -0,0 +1,36 @@
version: "3.9"
services:
sqlcoder-tgi:
image: ghcr.io/huggingface/text-generation-inference:2.1.0
container_name: sqlcoder-tgi
restart: unless-stopped
ports:
- "8080:80"
environment:
# Set your Hugging Face token to pull gated models
HUGGING_FACE_HUB_TOKEN: ${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}
# Pin to the 3090 (adjust if your GPU order differs)
CUDA_VISIBLE_DEVICES: "0"
DISABLE_FLASH_ATTENTION: "1"
CUDA_LAUNCH_BLOCKING: "1"
command:
- "--model-id=defog/sqlcoder-7b-2"
- "--dtype=float16"
- "--max-total-tokens=6144"
- "--max-input-length=4096"
- "--max-batch-prefill-tokens=4560"
- "--cuda-memory-fraction=0.9"
- "--trust-remote-code"
volumes:
- model-cache:/data
deploy:
resources:
reservations:
devices:
- capabilities: [gpu]
count: 1
driver: nvidia
volumes:
model-cache:

View File

@@ -0,0 +1 @@
"""Utilities for extracting database context artifacts for the SQL agent."""

View File

@@ -0,0 +1,5 @@
from .cli import main
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,46 @@
"""Command-line interface for database context extraction jobs."""
from __future__ import annotations
import argparse
from pathlib import Path
from . import schema_snapshot
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Extract schema and contextual artifacts for the SQL agent.",
)
parser.add_argument(
"--schema",
default=None,
help="Optional SQL Server schema to filter on (defaults to all schemas).",
)
parser.add_argument(
"--output",
default="db_agent/context/schema.json",
help="Path to write the schema JSON document.",
)
parser.add_argument(
"--job",
choices=["schema"],
default="schema",
help="Extraction job to run (currently only 'schema').",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
output_path = Path(args.output)
if args.job == "schema":
result = schema_snapshot.run(schema=args.schema, output=output_path)
print(f"Schema document written to {result}")
else:
raise RuntimeError(f"Unsupported job: {args.job}")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,175 @@
"""Extract schema metadata from the SugarScale MSSQL database."""
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List
import sqlalchemy as sa
from sqlalchemy.engine import Engine
from .settings import DbSettings
@dataclass
class TableColumn:
table_schema: str
table_name: str
column_name: str
data_type: str
is_nullable: bool
column_default: str | None
character_maximum_length: int | None
@dataclass
class ForeignKeyRelation:
source_schema: str
source_table: str
source_column: str
target_schema: str
target_table: str
target_column: str
def create_engine(settings: DbSettings) -> Engine:
connection_uri = (
"mssql+pyodbc:///?odbc_connect=" + sa.engine.url.quote_plus(settings.connection_string())
)
return sa.create_engine(connection_uri, fast_executemany=True)
def fetch_columns(engine: Engine, schema: str | None = None) -> List[TableColumn]:
columns: List[TableColumn] = []
query = sa.text(
"""
SELECT
TABLE_SCHEMA,
TABLE_NAME,
COLUMN_NAME,
DATA_TYPE,
IS_NULLABLE,
COLUMN_DEFAULT,
CHARACTER_MAXIMUM_LENGTH
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (:schema IS NULL OR TABLE_SCHEMA = :schema)
ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION
"""
)
with engine.connect() as conn:
result = conn.execute(query, {"schema": schema})
for row in result:
columns.append(
TableColumn(
table_schema=row.TABLE_SCHEMA,
table_name=row.TABLE_NAME,
column_name=row.COLUMN_NAME,
data_type=row.DATA_TYPE,
is_nullable=(row.IS_NULLABLE == "YES"),
column_default=row.COLUMN_DEFAULT,
character_maximum_length=row.CHARACTER_MAXIMUM_LENGTH,
)
)
return columns
def fetch_foreign_keys(engine: Engine, schema: str | None = None) -> List[ForeignKeyRelation]:
relations: List[ForeignKeyRelation] = []
query = sa.text(
"""
SELECT
fk_tab.name AS source_table,
fk_col.name AS source_column,
fk_sch.name AS source_schema,
pk_tab.name AS target_table,
pk_col.name AS target_column,
pk_sch.name AS target_schema
FROM sys.foreign_key_columns fkc
INNER JOIN sys.tables fk_tab ON fkc.parent_object_id = fk_tab.object_id
INNER JOIN sys.schemas fk_sch ON fk_tab.schema_id = fk_sch.schema_id
INNER JOIN sys.columns fk_col ON fkc.parent_object_id = fk_col.object_id AND fkc.parent_column_id = fk_col.column_id
INNER JOIN sys.tables pk_tab ON fkc.referenced_object_id = pk_tab.object_id
INNER JOIN sys.schemas pk_sch ON pk_tab.schema_id = pk_sch.schema_id
INNER JOIN sys.columns pk_col ON fkc.referenced_object_id = pk_col.object_id AND fkc.referenced_column_id = pk_col.column_id
WHERE (:schema IS NULL OR fk_sch.name = :schema)
ORDER BY fk_sch.name, fk_tab.name
"""
)
with engine.connect() as conn:
result = conn.execute(query, {"schema": schema})
for row in result:
relations.append(
ForeignKeyRelation(
source_schema=row.source_schema,
source_table=row.source_table,
source_column=row.source_column,
target_schema=row.target_schema,
target_table=row.target_table,
target_column=row.target_column,
)
)
return relations
def assemble_schema_document(columns: Iterable[TableColumn], relations: Iterable[ForeignKeyRelation]) -> Dict[str, Any]:
schema_doc: Dict[str, Any] = {"tables": {}}
for col in columns:
table_key = f"{col.table_schema}.{col.table_name}"
table_entry = schema_doc["tables"].setdefault(
table_key,
{
"schema": col.table_schema,
"name": col.table_name,
"columns": [],
"relationships": [],
},
)
table_entry["columns"].append(
{
"name": col.column_name,
"type": col.data_type,
"nullable": col.is_nullable,
"default": col.column_default,
"max_length": col.character_maximum_length,
}
)
for rel in relations:
table_key = f"{rel.source_schema}.{rel.source_table}"
table_entry = schema_doc["tables"].setdefault(
table_key,
{
"schema": rel.source_schema,
"name": rel.source_table,
"columns": [],
"relationships": [],
},
)
table_entry["relationships"].append(
{
"target": f"{rel.target_schema}.{rel.target_table}",
"source_column": rel.source_column,
"target_column": rel.target_column,
}
)
return schema_doc
def write_schema_json(output_path: Path, schema_doc: Dict[str, Any]) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("w", encoding="utf-8") as f:
json.dump(schema_doc, f, indent=2, sort_keys=True)
def run(schema: str | None = None, output: Path | None = None) -> Path:
settings = DbSettings.from_env()
engine = create_engine(settings)
columns = fetch_columns(engine, schema=schema)
relations = fetch_foreign_keys(engine, schema=schema)
schema_doc = assemble_schema_document(columns, relations)
output_path = output or Path("db_agent/context/schema.json")
write_schema_json(output_path, schema_doc)
return output_path

View File

@@ -0,0 +1,81 @@
"""Configuration helpers for connecting to the MSSQL sandbox."""
from __future__ import annotations
import os
from dataclasses import dataclass
@dataclass(frozen=True)
class DbSettings:
"""Environment-driven connection settings for SQL Server.
Required variables:
- DB_SERVER (e.g.,
- DB_DATABASE (e.g., "SugarScale_Lasuca")
- DB_USERNAME (database login)
- DB_PASSWORD (database password)
Optional overrides:
- DB_DRIVER (defaults to "$env")
- DB_ENCRYPT ("true" to enable TLS)
- DB_TRUST_CERT ("true" to trust the server certificate)
"""
server: str
database: str
username: str
password: str
driver: str = "ODBC Driver 18 for SQL Server"
encrypt: bool = True
trust_server_certificate: bool = True
@classmethod
def from_env(cls) -> "DbSettings":
missing: list[str] = []
server = os.getenv("DB_SERVER")
if not server:
missing.append("DB_SERVER")
database = os.getenv("DB_DATABASE")
if not database:
missing.append("DB_DATABASE")
username = os.getenv("DB_USERNAME")
if not username:
missing.append("DB_USERNAME")
password = os.getenv("DB_PASSWORD")
if not password:
missing.append("DB_PASSWORD")
if missing:
raise RuntimeError(
"Missing required environment variables: " + ", ".join(missing)
)
driver = os.getenv("DB_DRIVER", "ODBC Driver 18 for SQL Server")
encrypt = os.getenv("DB_ENCRYPT", "true").lower() == "true"
trust = os.getenv("DB_TRUST_CERT", "true").lower() == "true"
return cls(
server=server,
database=database,
username=username,
password=password,
driver=driver,
encrypt=encrypt,
trust_server_certificate=trust,
)
def connection_string(self) -> str:
parts = [
f"DRIVER={{{self.driver}}}",
f"SERVER={self.server}",
f"DATABASE={self.database}",
f"UID={self.username}",
f"PWD={self.password}",
]
if self.encrypt:
parts.append("Encrypt=yes")
if self.trust_server_certificate:
parts.append("TrustServerCertificate=yes")
parts.append("MARS_Connection=yes")
return ";".join(parts)

View File

@@ -0,0 +1,67 @@
# Database Agent Knowledge Prep
Use this checklist when preparing context for the natural-language SQL agent targeting our MSSQL sandbox.
## 1. Schema Catalog
- Summarize each table: name, purpose, primary keys, row granularity.
- List columns with data types and short descriptions; call out nullable fields.
- Document relationships: foreign-key paths, cardinality, and join direction.
- Recommended format (YAML example):
```yaml
tables:
production_events:
description: "Aggregated production metrics per line and hour."
columns:
- name: event_id
type: INT IDENTITY PRIMARY KEY
description: "Unique row ID."
nullable: false
- name: line_id
type: INT
description: "Foreign key to lines.id."
nullable: false
relationships:
- target: lines.id
via: production_events.line_id
cardinality: many-to-one
```
## 2. Business Semantics
- Provide glossary entries translating operator language to schema terms (e.g., "downtime" = `status_code` IN ('STOP','IDLE')).
- Explain derived metrics (OEE, throughput, scrap rate) and point to source columns.
- Note standard filters such as default time windows or equipment subsets.
## 3. Constraints & Guardrails
- Specify the read-only SQL credential and allowed schemas.
- List restricted tables, PII fields, or aggregates-only policies.
- Define execution limits: use `TOP` N defaults, row caps, timeout expectations.
- Capture timezone rules (UTC vs. local), especially for reporting dates.
## 4. Column Value Hints
- Enumerate controlled vocabularies (status codes, shift codes, unit names).
- Record measurement units and typical ranges to guide threshold suggestions.
- Mention any sentinel values representing missing or error states.
## 5. Worked Examples
- Include natural-language question, approved SQL, and a quick rationale.
- Aim for 5-10 examples covering joins, filters, time windows, aggregations.
- Store as Markdown table or JSON array for programmatic retrieval:
```json
[
{
"question": "Show top 10 downtime events last week for line A.",
"sql": "SELECT TOP (10) event_id, start_time, duration_min FROM downtime_events WHERE line_id = 'A' AND start_time >= DATEADD(day, -7, SYSUTCDATETIME()) ORDER BY duration_min DESC;",
"notes": "Uses UTC timestamps, filters to line A, orders by duration."
}
]
```
## 6. Delivery Format
- Consolidate the above into a single Markdown or JSON document checked into `db_agent/context/`.
- Keep the file under 20 KB so it can be injected directly into prompts; otherwise plan a retrieval step.
- Version changes alongside schema migrations so the agent stays accurate.
## 7. Maintenance Tips
- Regenerate the schema summary whenever the database structure changes (use `INFORMATION_SCHEMA`).
- Review logs of model-generated SQL to discover recurring gaps in the context.
- Expand the glossary with real user questions and clarifications over time.

View File

@@ -0,0 +1,52 @@
"""Helpers for recording agent interactions to disk."""
from __future__ import annotations
import json
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
DEFAULT_LOG_PATH = Path("db_agent/logs/query_log.jsonl")
def log_interaction(
*,
question: str,
generated_sql: str,
summary: str,
sanitized_sql: Optional[str] = None,
row_count: Optional[int] = None,
execution_status: Optional[str] = None,
execution_error: Optional[str] = None,
raw_response: Optional[str] = None,
user_feedback: Optional[str] = None,
log_path: Path | None = None,
metadata: Optional[dict[str, Any]] = None,
) -> Path:
"""Append a single interaction entry to a JSONL log."""
path = log_path or DEFAULT_LOG_PATH
path.parent.mkdir(parents=True, exist_ok=True)
entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"question": question,
"generated_sql": generated_sql,
"summary": summary,
"sanitized_sql": sanitized_sql,
"row_count": row_count,
"execution_status": execution_status,
"execution_error": execution_error,
"raw_response": raw_response,
"user_feedback": user_feedback,
}
if metadata:
entry["metadata"] = metadata
# Remove None values for cleaner logs
entry = {key: value for key, value in entry.items() if value is not None}
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(entry, ensure_ascii=False) + "\n")
return path

View File

@@ -0,0 +1,259 @@
{"timestamp": "2025-10-18T04:29:01.528021+00:00", "question": "How many loads were completed yesterday?", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"tables_hint": ["dbo.SugarLoadData"], "execution_requested": false}}
{"timestamp": "2025-10-18T04:35:54.612705+00:00", "question": "How many loads were completed yesterday?", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"tables_hint": ["dbo.SugarLoadData"], "execution_requested": true, "columns": ["load_count"], "preview_rows": 1}}
{"timestamp": "2025-10-18T04:44:22.465579+00:00", "question": "What was the heaviest load yesterday?", "generated_sql": "{\"sql\": SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);, \"summary\": \"The heaviest load yesterday was 88,000 pounds.\"}", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.SugarLoaddata"]}}
{"timestamp": "2025-10-18T04:45:35.777925+00:00", "question": "What was the heaviest load yesterday?", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoaddata"]}}
{"timestamp": "2025-10-18T04:47:25.880870+00:00", "question": "how many loads today", "generated_sql": "Answer: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:47:58.248895+00:00", "question": "how many loads today", "generated_sql": "Answer: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:51:27.201815+00:00", "question": "how many loads this week", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, 1, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:52:07.641419+00:00", "question": "how many loads this week", "generated_sql": "{\"sql\": SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:52:22.427721+00:00", "question": "how many loads this week", "generated_sql": "{\"sql\": SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:52:32.431951+00:00", "question": "how many loads this week", "generated_sql": "{\"sql\": SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:52:54.585002+00:00", "question": "how many loads today", "generated_sql": "Answer: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:53:24.359951+00:00", "question": "how many loads today", "generated_sql": "Answer: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:55:16.554311+00:00", "question": "how many loads today", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:55:24.064499+00:00", "question": "how many loads today", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:55:45.770169+00:00", "question": "how many loads this week", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, 1, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, 1, CAST(SYSDATETIME() AS date))", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:56:36.711324+00:00", "question": "how many loads this past monday", "generated_sql": "{\"sql\": SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -7, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date) AND EXTRACT(dow FROM DateOut) = 1;, \"summary\": \"There were 7 loads on Monday.\"}", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:57:48.978022+00:00", "question": "what was the heaviest load last week", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME());", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:58:24.756279+00:00", "question": "what was the heaviest load last week.", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME());", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:58:30.747532+00:00", "question": "what was the heaviest load last week.", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME());", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T04:58:36.367704+00:00", "question": "what was the heaviest load last week.", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date))", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T05:01:57.321230+00:00", "question": "loads", "generated_sql": "SELECT COUNT(*) AS total_loads FROM dbo.SugarLoadData;", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS total_loads FROM dbo.SugarLoadData", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": null}}
{"timestamp": "2025-10-18T05:02:08.225378+00:00", "question": "loads today", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": null}}
{"timestamp": "2025-10-18T05:02:56.822781+00:00", "question": "heaviest load last week", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date))", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": null}}
{"timestamp": "2025-10-18T05:13:13.202846+00:00", "question": "loads yesterday", "generated_sql": "that were not completed.\n SQL: SELECT COUNT(*) AS incomplete_loads FROM dbo.SugarLoadData WHERE DateOut IS NULL AND DateIn >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T05:13:57.315805+00:00", "question": "loads today", "generated_sql": "", "summary": "by hour of day.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T05:15:21.045133+00:00", "question": "loads today", "generated_sql": "", "summary": "by company.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"]}}
{"timestamp": "2025-10-18T05:20:05.193354+00:00", "question": "how many loads today", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:20:27.141745+00:00", "question": "how many loads today", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text."}}
{"timestamp": "2025-10-18T05:20:39.737262+00:00", "question": "how many loads today", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text."}}
{"timestamp": "2025-10-18T05:20:41.659656+00:00", "question": "how many loads today", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text."}}
{"timestamp": "2025-10-18T05:23:08.515321+00:00", "question": "how many loads yesterday", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": null, "llm_warning": null}}
{"timestamp": "2025-10-18T05:27:15.090465+00:00", "question": "how many loads today", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model did not return a valid SELECT statement; execution skipped."}}
{"timestamp": "2025-10-18T05:27:26.874405+00:00", "question": "how many loads today", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:27:36.059809+00:00", "question": "how many loads today", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model did not return a valid SELECT statement; execution skipped."}}
{"timestamp": "2025-10-18T05:27:49.287435+00:00", "question": "how many loads today", "generated_sql": "?\n SQL query: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model did not return a valid SELECT statement; execution skipped."}}
{"timestamp": "2025-10-18T05:31:49.883529+00:00", "question": "how many loads today", "generated_sql": "?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:32:13.445086+00:00", "question": "how many loads yesterday", "generated_sql": "?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:34:47.617732+00:00", "question": "how many loads yesterday", "generated_sql": "?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:35:08.187517+00:00", "question": "how many loads yesterday", "generated_sql": "?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:35:33.179333+00:00", "question": "loads yesterday", "generated_sql": ".\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:35:48.883049+00:00", "question": "loads yesterday", "generated_sql": ".\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:36:57.638273+00:00", "question": "loads yesterday", "generated_sql": ".\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:37:03.365771+00:00", "question": "loads yesterday", "generated_sql": ".\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:37:23.700969+00:00", "question": "loads today", "generated_sql": "by company.\n SQL: SELECT TCompanyName, COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date) GROUP BY TCompanyName;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:38:23.520274+00:00", "question": "how many loads today", "generated_sql": "?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date) AND DateOut < CAST(SYSDATETIME() AS date) + INTERVAL '1 day';", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:41:26.380665+00:00", "question": "how many loads today", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:41:43.575137+00:00", "question": "how many loads yesterday", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:42:01.397903+00:00", "question": "how many sugar loads yesterday", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar';", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:42:30.020874+00:00", "question": "how many sugar loads monday", "generated_sql": "to friday?\n SQL: SELECT COUNT(*) AS total_loads FROM dbo.SugarLoadData WHERE EXTRACT(dow FROM DateOut) BETWEEN 1 AND 5 AND CAST(DateOut AS DATE) = CAST(SYSDATETIME() AS DATE);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:43:13.781796+00:00", "question": "how many sugar loads this past monday", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -7, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar';", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -7, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:43:28.190660+00:00", "question": "how many sugar loads this past tuesday", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar';", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND LoadType = 'Sugar'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:44:06.905858+00:00", "question": "what was the heaviest load this week?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, -1, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, -1, CAST(SYSDATETIME() AS date))", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:44:23.020379+00:00", "question": "what was the heaviest load last week?", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME());", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:44:34.759816+00:00", "question": "what was the heaviest load this week?", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, -1, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(week, -1, CAST(SYSDATETIME() AS date))", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:45:18.288731+00:00", "question": "what was the heaviest load from 10/1 to 10/18?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2020-10-01' AND '2020-10-18';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2020-10-01' AND '2020-10-18'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:45:31.894904+00:00", "question": "what was the heaviest load from 10/1 to 10/18?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2020-10-01' AND '2020-10-18';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2020-10-01' AND '2020-10-18'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:46:35.269288+00:00", "question": "what was the heaviest load from 10/1/25 to 10/18/25?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-18';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-18'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:46:55.001426+00:00", "question": "what was the lightest load from 10/1/25 to 10/18/25?", "generated_sql": "", "summary": "{\"generated_text\":\"\"}", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "LLM response missing generated_text field; returning raw text. Preview: {\"generated_text\":\"\"} Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:47:05.775303+00:00", "question": "what was the lightest load from 10/1/25 to 10/18/25?", "generated_sql": "", "summary": "{\"generated_text\":\"\"}", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "LLM response missing generated_text field; returning raw text. Preview: {\"generated_text\":\"\"} Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T05:47:32.286521+00:00", "question": "what was the heaviest load from 10/1/25 to 10/9/25?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-09';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-09'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:47:49.570488+00:00", "question": "what was the heaviest load from 10/1/25 to 10/3/25?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-03';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM SugarLoadData WHERE DateOut BETWEEN '2025-10-01' AND '2025-10-03'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:48:03.258613+00:00", "question": "what was the heaviest load from 10/4/25 to 10/6/25?", "generated_sql": "SELECT MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-04' AND '2025-10-06';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS heaviest_load FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-04' AND '2025-10-06'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:48:17.686387+00:00", "question": "what was the heaviest load from 10/4/25 to 10/5/25?", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-04' AND '2025-10-05';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-04' AND '2025-10-05'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T05:48:32.284279+00:00", "question": "what was the heaviest load from 10/7/25 to 10/9/25?", "generated_sql": "SELECT MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-07' AND '2025-10-09';", "summary": "", "sanitized_sql": "SELECT TOP (500) MAX(GrossWt) AS max_gross_weight FROM dbo.SugarLoadData WHERE DateOut BETWEEN '2025-10-07' AND '2025-10-09'", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:24:00.713687+00:00", "question": "How many loads over 100000 yesterday", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND GrossWt > 100000;", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND GrossWt > 100000", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:24:22.328815+00:00", "question": "List all loads over 100000 yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE GrossWt > 100000 AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) * FROM dbo.SugarLoadData WHERE GrossWt > 100000 AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 6, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:25:13.769895+00:00", "question": "List all loads over 100000 yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND GrossWt > 100000;", "summary": "", "sanitized_sql": "SELECT TOP (500) * FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND GrossWt > 100000", "row_count": 6, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:25:47.952375+00:00", "question": "List all loads between 90000 and 80000 yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE ScaleWT BETWEEN 90000 AND 80000 AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime);", "summary": "", "sanitized_sql": "SELECT TOP (500) * FROM dbo.SugarLoadData WHERE ScaleWT BETWEEN 90000 AND 80000 AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)", "row_count": 0, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:26:25.273525+00:00", "question": "List all loads between 90000 and 100000 yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE ScaleWT BETWEEN 90000 AND 100000 AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) ORDER BY DateOut NULLS LAST;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:26:57.761426+00:00", "question": "List all loads from yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T14:27:05.021191+00:00", "question": "List all loads from yesterday", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) * FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 22, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Initial attempt failed: LLM output could not be parsed; returning raw text. Preview: .. Retried with formatting reminder."}}
{"timestamp": "2025-10-18T14:27:45.472453+00:00", "question": "List all loads from 10/16/25", "generated_sql": "", "summary": "to 10/17/25.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: to 10/17/25. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:28:01.189092+00:00", "question": "List all loads from 10/16/25", "generated_sql": "", "summary": "00 to 10/17/2500.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: 00 to 10/17/2500. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:39:53.987644+00:00", "question": "List all loads from 10/16/25", "generated_sql": "", "summary": "62 to 10/17/2562.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: 62 to 10/17/2562. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:40:19.791577+00:00", "question": "List all loads from monday", "generated_sql": "to friday.\n SQL: SELECT * FROM dbo.SugarLoadData WHERE EXTRACT(dow FROM DateOut) BETWEEN 1 AND 5;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:40:57.479412+00:00", "question": "List all loads from 10/15/25", "generated_sql": "", "summary": "62 to 10/20/2562.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: 62 to 10/20/2562. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:41:18.647455+00:00", "question": "List all loads from 10/15/2025", "generated_sql": "to 10/20/2025.\n SQL: SELECT * FROM dbo.SugarLoadData WHERE DateIn BETWEEN '2025-10-15' AND '2025-10-20';", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:41:49.205697+00:00", "question": "List all loads from 10/15/2025 only", "generated_sql": "", "summary": ".", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: . Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:42:15.314362+00:00", "question": "List all loads from the past week", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": "SELECT TOP (500) * FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date))", "row_count": 233, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Initial attempt failed: LLM output could not be parsed; returning raw text. Preview: .. Retried with formatting reminder."}}
{"timestamp": "2025-10-18T14:43:27.908517+00:00", "question": "List all loads from ralph callier", "generated_sql": "'s company in the last 24 hours.\n SQL: SELECT * FROM dbo.SugarLoadData l WHERE l.TCompanyName ILIKE '%RALPH%CALLIER%' AND l.DateOut >= DATEADD(hour, -24, SYSDATETIME()) ORDER BY l.DateOut NULLS LAST;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:50:03.104069+00:00", "question": "List all loads from ralph callier", "generated_sql": "'s company in the last 24 hours.\n SQL: SELECT * FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE v.TCompanyName ILIKE '%ralph%callier%' AND l.DateOut >= DATEADD(hour, -24, SYSDATETIME()) ORDER BY l.DateOut NULLS LAST;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:50:42.250044+00:00", "question": "List all loads from company ralph callier", "generated_sql": "in the last 24 hours.\n SQL: SELECT * FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%ralph%callier%' AND DateOut >= CAST(DATEADD(hour, -24, CAST(SYSDATETIME() AS date)) AS datetime) ORDER BY DateOut NULLS LAST;", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:51:04.350689+00:00", "question": "List all loads from company Ralph Callier", "generated_sql": "in the last 7 days.\n SQL: SELECT * FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%Ralph%Callier%' AND DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T14:51:50.844953+00:00", "question": "List all loads from company Ralph Callier", "generated_sql": "in the last 7 days.\n SQL: SELECT * FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%Ralph%Callier%' AND DateOut >= DATEADD(day, -7, CAST(SYSDATETIME() AS date));", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T16:54:56.079797+00:00", "question": "How many loads from Ralph callier", "generated_sql": "were delivered in the last 24 hours?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= DATEADD(hour, -24, CAST(SYSDATETIME() AS date)) AND TCompanyName ILIKE '%Ralph%callier%';", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T16:59:27.498329+00:00", "question": "How many loads from Ralph callier", "generated_sql": "were delivered yesterday?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) AND TCompanyName ILIKE '%Ralph%callier%';", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T16:59:55.618771+00:00", "question": "How many loads from Ralph callier from all time", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": null, "llm_warning": "LLM output could not be parsed; returning raw text. Preview: ? Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T17:00:04.917741+00:00", "question": "How many loads from Ralph callier from all time", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: ? Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T17:00:12.836444+00:00", "question": "How many loads from Ralph callier from all time", "generated_sql": "", "summary": "?", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "LLM output could not be parsed; returning raw text. Preview: ? Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T17:00:24.283622+00:00", "question": "How many loads from Ralph callier", "generated_sql": "were delivered today?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date) AND TCompanyName ILIKE '%Ralph%callier%';", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T17:00:46.640184+00:00", "question": "How many loads from Ralph callier", "generated_sql": "were delivered today?\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%Ralph%callier%' AND DateOut >= CAST(SYSDATETIME() AS date) AND DateOut < CAST(SYSDATETIME() + INTERVAL '1 day' AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model response did not include a valid SELECT statement. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T17:01:06.370459+00:00", "question": "How many loads from Ralph callier were delivered today", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%Ralph%callier%' AND DateOut >= CAST(SYSDATETIME() AS date) AND DateOut < CAST(SYSDATETIME() + INTERVAL '1 day' AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Initial attempt failed: LLM output could not be parsed; returning raw text. Preview: ?. Retried with formatting reminder."}}
{"timestamp": "2025-10-18T19:09:05.990023+00:00", "question": "Find loads from Ralph Callier", "generated_sql": "'s company in the last 24 hours.\n SQL: SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE v.TCompanyName ILIKE '%Ralph%Callier%' AND l.DateOut >= DATEADD(hour, -24, SYSDATETIME());", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Model added an unrequested time filter. Ensure future responses only add filters present in the question. Second attempt also failed to produce a valid SELECT statement."}}
{"timestamp": "2025-10-18T19:20:37.648813+00:00", "question": "Find loads from Ralph Callier", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE TCompanyName ILIKE '%RALPH CALLIER%' AND DateOut >= CAST(DATEADD(day, -14, SYSDATETIME()) AS date);", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T19:25:07.932494+00:00", "question": "Find loads from Ralph Callier", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE UPPER(v.TCompanyName) LIKE UPPER('%RALPH%CALLIER%') AND l.DateOut >= CAST(SYSDATETIME() AS date);", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE UPPER(v.TCompanyName) LIKE UPPER('%RALPH%CALLIER%') AND l.DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T19:25:33.393615+00:00", "question": "Find loads from ralph callier", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE UPPER(v.TCompanyName) LIKE UPPER('%ralph%callier%') AND l.DateOut IS NOT NULL;", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData l JOIN dbo.SugarVehicles v ON l.VehicleId_Fk = v.VehicleId_Pk WHERE UPPER(v.TCompanyName) LIKE UPPER('%ralph%callier%') AND l.DateOut IS NOT NULL", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T19:26:17.092654+00:00", "question": "Lost all loads from ralph callier", "generated_sql": "SELECT COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE UPPER(TCompanyName) LIKE UPPER('%RALPH%CALLIER%') AND DateOut IS NULL;", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count FROM dbo.SugarLoadData WHERE UPPER(TCompanyName) LIKE UPPER('%RALPH%CALLIER%') AND DateOut IS NULL", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Attempt 1: LLM output could not be parsed; returning raw text. Preview: .; Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T22:38:21.424656+00:00", "question": "How many loads of sugar today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\n Summary: \"There are currently 0 loads of sugar today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": null, "llm_warning": null}}
{"timestamp": "2025-10-18T22:38:55.851817+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\n Summary: \"There are currently 0 loads today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": null, "llm_warning": null}}
{"timestamp": "2025-10-18T22:41:12.118065+00:00", "question": "How many loads today from ralph callier", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)\n AND UPPER(TCompanyName) LIKE UPPER('%ralph callier%');\n Summary: \"There are 0 loads today from Ralph Callier.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": null, "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T22:41:19.813140+00:00", "question": "How many loads today from ralph callier", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)\n AND UPPER(TCompanyName) LIKE UPPER('%ralph callier%');\n Summary: \"There are currently 0 loads from Ralph Callier today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T22:44:22.833620+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\n Summary: \"There are currently 0 loads today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:44:40.809277+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\n Summary: \"There are currently 0 loads today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:45:09.238103+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\n Summary: \"There are currently 0 loads today.\"", "summary": "", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:47:17.025283+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "There are currently 0 loads today.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:47:22.458532+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "There are currently 0 loads today.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:47:40.158932+00:00", "question": "How many loads yesterday", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "There were 5 loads completed yesterday.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:48:13.677738+00:00", "question": "Liat all loads from ralph callier", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"TCompanyName\" ILIKE '%RALPH CALLIER%';", "summary": "Retrieving all load data for 'RALPH CALLIER'.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:48:55.477012+00:00", "question": "Liat all loads from ralph callier", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"TCompanyName\" ILIKE '%RALPH CALLIER%';", "summary": "Retrieving all load data for 'RALPH CALLIER'.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:50:52.444577+00:00", "question": "Liat all loads from ralph callier", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%RALPH CALLIER%');", "summary": "Retrieving all load data for 'RALPH CALLIER'.", "sanitized_sql": null, "row_count": null, "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T22:51:05.166730+00:00", "question": "Liat all loads from ralph callier", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%RALPH CALLIER%');", "summary": "Retrieving all load data for 'RALPH CALLIER'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%RALPH CALLIER%')", "row_count": 67, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-18T22:51:56.087879+00:00", "question": "Liat all loads from 10/12/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00';", "summary": "Retrieving all loads that occurred on 10/12/25.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'", "row_count": 16, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:52:17.374235+00:00", "question": "Liat all loads from 10/12/25 over 100000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND GrossWt > 100000;", "summary": "Retrieving all loads that occurred on or after 10/12/25 and had a gross weight over 100000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND GrossWt > 100000", "row_count": 23, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T22:52:59.798088+00:00", "question": "Liat all loads from 10/12/25 to 10/13/25 over 100000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00' AND DateOut < '2025-10-14 00:00:00' AND GrossWt > 100000;", "summary": "Selecting all loads from 10/12/25 to 10/13/25 with a gross weight over 100000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00' AND DateOut < '2025-10-14 00:00:00' AND GrossWt > 100000", "row_count": 6, "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-18T23:15:45.718718+00:00", "question": "How many loads over 100000", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE GrossWt > 100000;\n Summary: \"There are 0 loads over 100000.\"", "summary": "", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE GrossWt > 100000;\\n Summary: \\\"There are 0 loads over 100000.\\\"\", \"summary\": \"\", \"llm_warning\": \"Attempt 1: Model response did not include a valid SELECT statement.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Attempt 1: Model response did not include a valid SELECT statement."}}
{"timestamp": "2025-10-18T23:18:13.423493+00:00", "question": "How many loads over 100000", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE GrossWt > 100000;", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE GrossWt > 100000", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE GrossWt > 100000;\", \"summary\": \"\", \"llm_warning\": \"Postprocess: Removed unrequested date/time filters from SQL output.; Attempt 1: Model response did not include a valid SELECT statement.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Removed unrequested date/time filters from SQL output.; Attempt 1: Model response did not include a valid SELECT statement."}}
{"timestamp": "2025-10-19T00:19:34.490018+00:00", "question": "List all loads on 10/12/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00';", "summary": "The SQL query lists all loads that occurred on October 12, 2025.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-13 00:00:00';\", \"summary\": \"The SQL query lists all loads that occurred on October 12, 2025.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T00:20:36.968497+00:00", "question": "List all loads on 10/12/25 hauled by big dog", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%big dog%')\n );", "summary": "The SQL query lists all loads that occurred on 10/12/25 and were hauled by vehicles associated with the company name 'Big Dog'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%big dog%')\n )", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-13 00:00:00'\\n AND VehicleId_Fk IN (\\n SELECT VehicleId_Pk\\n FROM dbo.SugarVehicles\\n WHERE UPPER(TCompanyName) LIKE UPPER('%big dog%')\\n );\", \"summary\": \"The SQL query lists all loads that occurred on 10/12/25 and were hauled by vehicles associated with the company name 'Big Dog'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T00:20:50.601977+00:00", "question": "List all loads on 10/12/25 hauled by bigdog", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdog%')\n );", "summary": "The SQL query lists all loads that occurred on 10/12/25 and were hauled by vehicles associated with the company name 'bigdog'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdog%')\n )", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-13 00:00:00'\\n AND VehicleId_Fk IN (\\n SELECT VehicleId_Pk\\n FROM dbo.SugarVehicles\\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdog%')\\n );\", \"summary\": \"The SQL query lists all loads that occurred on 10/12/25 and were hauled by vehicles associated with the company name 'bigdog'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T00:21:21.343228+00:00", "question": "List all loads on 10/12/25 hauled by csc", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%csc%');", "summary": "The SQL query lists all loads that occurred on 10/12/25 and were hauled by 'csc'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%csc%')", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-13 00:00:00'\\n AND UPPER(TCompanyName) LIKE UPPER('%csc%');\", \"summary\": \"The SQL query lists all loads that occurred on 10/12/25 and were hauled by 'csc'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T00:53:01.274866+00:00", "question": "List all loads on 10/14/25 hauled by csc", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%csc%');", "summary": "The SQL query lists all loads that occurred on 10/14/25 and were hauled by 'csc'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%csc%')", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-14 00:00:00'\\n AND DateOut < '2025-10-15 00:00:00'\\n AND UPPER(TCompanyName) LIKE UPPER('%csc%');\", \"summary\": \"The SQL query lists all loads that occurred on 10/14/25 and were hauled by 'csc'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T00:54:53.249509+00:00", "question": "List all loads that have gs in the vehicle name", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%gs%')\n );", "summary": "Retrieving all loads associated with vehicles whose company names contain 'gs'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%gs%')\n )", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (\\n SELECT VehicleId_Pk\\n FROM dbo.SugarVehicles\\n WHERE UPPER(TCompanyName) LIKE UPPER('%gs%')\\n );\", \"summary\": \"Retrieving all loads associated with vehicles whose company names contain 'gs'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T00:55:32.113502+00:00", "question": "List all loads that have gs in the vehicle id", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%gs%';", "summary": "Retrieving all loads with 'gs' in the vehicle id.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%gs%'", "row_count": 71, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk LIKE '%gs%';\", \"summary\": \"Retrieving all loads with 'gs' in the vehicle id.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T00:56:02.539411+00:00", "question": "List all loads that have callier in the vehicle id", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%callier%';", "summary": "Retrieving all load data for vehicles with 'callier' in their identifier.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%callier%'", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk LIKE '%callier%';\", \"summary\": \"Retrieving all load data for vehicles with 'callier' in their identifier.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T00:56:21.164487+00:00", "question": "List all loads that have laca in the vehicle id", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%laca%';", "summary": "Retrieving all loads with 'laca' in the vehicle ID.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%laca%'", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk LIKE '%laca%';\", \"summary\": \"Retrieving all loads with 'laca' in the vehicle ID.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T00:57:41.163029+00:00", "question": "List all loads that have bd in the vehicle id", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%bd%';", "summary": "Retrieving all load data for vehicles with 'bd' in their identifier.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk LIKE '%bd%'", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk LIKE '%bd%';\", \"summary\": \"Retrieving all load data for vehicles with 'bd' in their identifier.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T00:58:56.525276+00:00", "question": "List all loads that are between 90000 and 92000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE GrossWt BETWEEN 90000 AND 92000;", "summary": "Listing all loads with gross weights between 90000 and 92000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE GrossWt BETWEEN 90000 AND 92000", "row_count": 88, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE GrossWt BETWEEN 90000 AND 92000;\", \"summary\": \"Listing all loads with gross weights between 90000 and 92000.\", \"llm_warning\": \"Attempt 1: Model response did not include a valid SELECT statement.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Attempt 1: Model response did not include a valid SELECT statement."}}
{"timestamp": "2025-10-19T01:07:11.573000+00:00", "question": "List all loads that are between 90000 and 92000\nAnd the company is bigdawg", "generated_sql": "SELECT *\nFROM dbo.SugarLoadData\nWHERE GrossWt BETWEEN 90000 AND 92000\n AND UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%');", "summary": "The SQL query lists all loads with a gross weight between 90000 and 92000 and the company name contains 'BIGDAWG'.", "sanitized_sql": "SELECT TOP (500) *\nFROM dbo.SugarLoadData\nWHERE GrossWt BETWEEN 90000 AND 92000\n AND UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%')", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\nFROM dbo.SugarLoadData\\nWHERE GrossWt BETWEEN 90000 AND 92000\\n AND UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%');\", \"summary\": \"The SQL query lists all loads with a gross weight between 90000 and 92000 and the company name contains 'BIGDAWG'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T01:15:17.775803+00:00", "question": "List all loads with a tare weight less than 30000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000;", "summary": "Retrieving all load data with a tare weight less than 30000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE \\\"TareWt\\\" < 30000;\", \"summary\": \"Retrieving all load data with a tare weight less than 30000.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T01:31:27.548741+00:00", "question": "Show me all loads under 30000", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\n FROM dbo.SugarLoadData\n WHERE GrossWt < 30000;", "summary": "Displaying all load data with a gross weight less than 30000 pounds.", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\\n FROM dbo.SugarLoadData\\n WHERE GrossWt < 30000;\", \"summary\": \"Displaying all load data with a gross weight less than 30000 pounds.\", \"llm_warning\": \"Attempt 1: Model response did not include a valid SELECT statement.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Attempt 1: Model response did not include a valid SELECT statement."}}
{"timestamp": "2025-10-19T01:31:39.506732+00:00", "question": "Show me all loads under 30000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE GrossWt < 30000;", "summary": "Displaying all loads with a gross weight less than 30000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE GrossWt < 30000", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE GrossWt < 30000;\", \"summary\": \"Displaying all loads with a gross weight less than 30000.\", \"llm_warning\": \"Attempt 1: Model response did not include a valid SELECT statement.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Attempt 1: Model response did not include a valid SELECT statement."}}
{"timestamp": "2025-10-19T01:32:54.438627+00:00", "question": "Show me all loads with a tare under 30000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000;", "summary": "Retrieving all load data with a tare weight less than 30000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE \\\"TareWt\\\" < 30000;\", \"summary\": \"Retrieving all load data with a tare weight less than 30000.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T01:33:08.391754+00:00", "question": "Show me all loads with a tare under 30000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000;", "summary": "Retrieving all load data with a tare weight less than 30000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE \"TareWt\" < 30000", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-19T02:16:49.993593+00:00", "question": "show me loads hauled by bigdawg between 10/12/25 and 10/14/25", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\n ORDER BY DateIn;", "summary": "The SQL query retrieves load data for loads hauled by 'BIGDAWG' between 10/12/25 and 10/14/25, ordered by the time of entry.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\n ORDER BY DateIn", "row_count": 17, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\\n ORDER BY DateIn;\", \"summary\": \"The SQL query retrieves load data for loads hauled by 'BIGDAWG' between 10/12/25 and 10/14/25, ordered by the time of entry.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:17:40.030692+00:00", "question": "show me loads hauled by bigdawg between 10/12/25 and 10/14/25 that are over 100000", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'\n AND GrossWt > 100000;", "summary": "Bigdawg has hauled 100000+ pound loads on 10/12/25 and 10/13/25.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'\n AND GrossWt > 100000", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, DateOut\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-15 00:00:00'\\n AND GrossWt > 100000;\", \"summary\": \"Bigdawg has hauled 100000+ pound loads on 10/12/25 and 10/13/25.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:18:03.083340+00:00", "question": "show me loads hauled by bigdawg between 10/12/25 and 10/14/25 that have a tare less than 30000", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\n )\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\n AND TareWt < 30000;", "summary": "Bigdawg loads with a tare less than 30000 from 10/12/25 to 10/14/25 are being listed.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\n )\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\n AND TareWt < 30000", "row_count": 2, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (\\n SELECT VehicleId_Pk\\n FROM dbo.SugarVehicles\\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\\n )\\n AND DateIn >= '2025-10-12' AND DateIn < '2025-10-15'\\n AND TareWt < 30000;\", \"summary\": \"Bigdawg loads with a tare less than 30000 from 10/12/25 to 10/14/25 are being listed.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:18:21.655909+00:00", "question": "show me loads hauled by bigdawg between 10/12/25 and 10/14/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-15 00:00:00';", "summary": "The SQL query retrieves all loads associated with vehicles registered to 'BIGDAWG' that occurred between 10/12/25 and 10/14/25.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-15 00:00:00';\", \"summary\": \"The SQL query retrieves all loads associated with vehicles registered to 'BIGDAWG' that occurred between 10/12/25 and 10/14/25.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:19:17.123783+00:00", "question": "show me loads hauled by bigdawg on 10/12/25 between 6am and noon", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 06:00:00'\n AND DateOut < '2025-10-12 12:00:00';", "summary": "The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' that occurred between 6am and noon on 10/12/25.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 06:00:00'\n AND DateOut < '2025-10-12 12:00:00'", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-12 06:00:00'\\n AND DateOut < '2025-10-12 12:00:00';\", \"summary\": \"The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' that occurred between 6am and noon on 10/12/25.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:19:34.232102+00:00", "question": "show me loads hauled by bigdawg on 10/12/25 between 6am and 12pm", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 06:00:00'\n AND DateOut < '2025-10-12 12:00:00';", "summary": "Here are the loads hauled by 'BIGDAWG' on 10/12/25 from 6am to 12pm.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 06:00:00'\n AND DateOut < '2025-10-12 12:00:00'", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-12 06:00:00'\\n AND DateOut < '2025-10-12 12:00:00';\", \"summary\": \"Here are the loads hauled by 'BIGDAWG' on 10/12/25 from 6am to 12pm.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:20:16.725795+00:00", "question": "show me loads hauled by bigdawg on 10/12/25 between 12am and 11pm", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 23:00:00';", "summary": "The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' from 10/12/25 from 12am to 11pm.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 23:00:00'", "row_count": 11, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-13 23:00:00';\", \"summary\": \"The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' from 10/12/25 from 12am to 11pm.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T02:21:20.618815+00:00", "question": "show me loads hauled by bigdawg on 10/13/25 between midnight and 4pm", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-13 16:00:00';", "summary": "The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' on October 13, 2025, between midnight and 4pm.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-13 16:00:00'", "row_count": 6, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= '2025-10-13 00:00:00'\\n AND DateOut < '2025-10-13 16:00:00';\", \"summary\": \"The SQL query retrieves all loads associated with the vehicle 'BIGDAWG' on October 13, 2025, between midnight and 4pm.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T15:40:24.058282+00:00", "question": "List Loads from today", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\n FROM dbo.SugarLoadData\n WHERE DateIn >= CAST(SYSDATETIME() AS date);", "summary": "Retrieving all loads from today, including their unique load ID, vehicle ID, gross weight, tare weight, net weight, and timestamps for entry and exit.", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut\\n FROM dbo.SugarLoadData\\n WHERE DateIn >= CAST(SYSDATETIME() AS date);\", \"summary\": \"Retrieving all loads from today, including their unique load ID, vehicle ID, gross weight, tare weight, net weight, and timestamps for entry and exit.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T15:45:33.273053+00:00", "question": "List Loads from today", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut, LoadType, TrailerTypeID, LoadingLocation, Destination, TCompanyName\n FROM dbo.SugarLoadData\n WHERE DateIn >= CAST(SYSDATETIME() AS date);", "summary": "Retrieving all loads from today, including their unique load ID, vehicle ID, gross weight, tare weight, net weight, date of entry, date of exit, load type, trailer type, loading location, destination, and hauling company.", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut, LoadType, TrailerTypeID, LoadingLocation, Destination, TCompanyName\\n FROM dbo.SugarLoadData\\n WHERE DateIn >= CAST(SYSDATETIME() AS date);\", \"summary\": \"Retrieving all loads from today, including their unique load ID, vehicle ID, gross weight, tare weight, net weight, date of entry, date of exit, load type, trailer type, loading location, destination, and hauling company.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T15:45:53.243340+00:00", "question": "List Loads from today", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateIn, DateOut, LoadType, TrailerTypeID, LoadingLocation, Destination, TCompanyName\n FROM dbo.SugarLoadData\n WHERE DateIn >= CAST(SYSDATETIME() AS date);", "summary": "Retrieving all loads from today, including their unique load ID, vehicle ID, gross weight, tare weight, net weight, date of entry, date of exit, load type, trailer type, loading location, destination, and hauling company.", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-19T16:39:04.312912+00:00", "question": "Show loads from today", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "Displaying all loads that occurred today.", "raw_response": "{\"sql\": \"SELECT * FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);\", \"summary\": \"Displaying all loads that occurred today.\"}", "metadata": {"source": "ui", "execute": false, "tables": null, "llm_warning": null}}
{"timestamp": "2025-10-19T16:39:39.195555+00:00", "question": "Show loads from today", "generated_sql": "SELECT * FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "Displaying all loads that occurred today.", "raw_response": "{\"sql\": \"SELECT * FROM dbo.SugarLoadData WHERE DateOut >= CAST(SYSDATETIME() AS date);\", \"summary\": \"Displaying all loads that occurred today.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T16:42:08.171902+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "There are currently no loads today.", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\", \"summary\": \"There are currently no loads today.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T16:42:32.990525+00:00", "question": "How many loads yesterday", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "There were 0 loads yesterday.", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(SYSDATETIME() AS date);\", \"summary\": \"There were 0 loads yesterday.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T16:43:02.625368+00:00", "question": "How many loads yesterday", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "There were 10 loads completed yesterday.", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(SYSDATETIME() AS date);\", \"summary\": \"There were 10 loads completed yesterday.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T16:43:44.730675+00:00", "question": "How many loads on 10/12/25", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-12 00:00:00'\n AND DateOut < '2025-10-13 00:00:00';", "summary": "The query counts the number of loads that occurred on October 12, 2025.", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-12 00:00:00'\\n AND DateOut < '2025-10-13 00:00:00';\", \"summary\": \"The query counts the number of loads that occurred on October 12, 2025.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T17:46:58.682007+00:00", "question": "How many loads today between 6am and now", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)\n AND DateOut < DATEADD(hour, 18, CAST(SYSDATETIME() AS date))\n AND DateIn >= DATEADD(hour, 6, CAST(SYSDATETIME() AS date));", "summary": "There are currently 0 loads recorded today between 6am and 6pm.", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(SYSDATETIME() AS date)\\n AND DateOut < DATEADD(hour, 18, CAST(SYSDATETIME() AS date))\\n AND DateIn >= DATEADD(hour, 6, CAST(SYSDATETIME() AS date));\", \"summary\": \"There are currently 0 loads recorded today between 6am and 6pm.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:09:14.413723+00:00", "question": "How many loads today between 6am and now", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)\n AND DateOut < DATEADD(hour, 18, CAST(SYSDATETIME() AS date))\n AND DateIn >= DATEADD(hour, 6, CAST(SYSDATETIME() AS date));", "summary": "There are currently 0 loads recorded from 6am to 6pm today.", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(SYSDATETIME() AS date)\\n AND DateOut < DATEADD(hour, 18, CAST(SYSDATETIME() AS date))\\n AND DateIn >= DATEADD(hour, 6, CAST(SYSDATETIME() AS date));\", \"summary\": \"There are currently 0 loads recorded from 6am to 6pm today.\"}", "metadata": {"source": "ui", "execute": false, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:10:11.243216+00:00", "question": "How many loads today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "There are currently 0 loads today.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\", \"summary\": \"There are currently 0 loads today.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:10:26.139512+00:00", "question": "How many loads yesterday", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "There were 0 loads yesterday.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(SYSDATETIME() AS date);\", \"summary\": \"There were 0 loads yesterday.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:10:45.461754+00:00", "question": "How many loads on 10/17/25", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-17 00:00:00'\n AND DateOut < '2025-10-18 00:00:00';", "summary": "The query counts the number of loads that occurred on October 17, 2025.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-17 00:00:00'\n AND DateOut < '2025-10-18 00:00:00'", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-17 00:00:00'\\n AND DateOut < '2025-10-18 00:00:00';\", \"summary\": \"The query counts the number of loads that occurred on October 17, 2025.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:11:13.730898+00:00", "question": "List all loads on 10/17/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-17 00:00:00'\n AND DateOut < '2025-10-18 00:00:00';", "summary": "The SQL query lists all loads that occurred on October 17, 2025.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-17 00:00:00'\n AND DateOut < '2025-10-18 00:00:00'", "row_count": 22, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-17 00:00:00'\\n AND DateOut < '2025-10-18 00:00:00';\", \"summary\": \"The SQL query lists all loads that occurred on October 17, 2025.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:11:34.914966+00:00", "question": "List all loads today", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "Retrieving all loads that occurred today.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 2, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\", \"summary\": \"Retrieving all loads that occurred today.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:12:10.603547+00:00", "question": "List all loads today", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "Retrieving all loads that occurred today.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 2, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\", \"summary\": \"Retrieving all loads that occurred today.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:40:05.788543+00:00", "question": "List all loads from yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the previous 24 hours, which is equivalent to yesterday's loads.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 9, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"Retrieving all load data from the previous 24 hours, which is equivalent to yesterday's loads.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:40:46.749299+00:00", "question": "List all loads from yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the previous 24 hours, which is equivalent to yesterday's loads.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-19T18:41:49.100940+00:00", "question": "How many total tons of sugar was hauled yesterday", "generated_sql": "SELECT SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "The total tons of sugar hauled yesterday is calculated by summing the \"Tons\" column from the \"dbo.SugarLoadData\" table for loads completed yesterday.", "sanitized_sql": "SELECT TOP (500) SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SUM(Tons) AS total_tons\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(SYSDATETIME() AS date);\", \"summary\": \"The total tons of sugar hauled yesterday is calculated by summing the \\\"Tons\\\" column from the \\\"dbo.SugarLoadData\\\" table for loads completed yesterday.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:42:06.693821+00:00", "question": "How many total tons of sugar was hauled yesterday", "generated_sql": "SELECT SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "The total tons of sugar hauled yesterday is calculated by summing the \"Tons\" column from the \"dbo.SugarLoadData\" table for loads completed yesterday.", "sanitized_sql": "SELECT TOP (500) SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date)", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-19T18:42:18.530959+00:00", "question": "How many total tons of sugar was hauled last week", "generated_sql": "SELECT SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())\n AND DateOut < DATEADD(day, -6, SYSDATETIME());", "summary": "The total tons of sugar hauled last week is calculated by summing the 'Tons' column from the 'dbo.SugarLoadData' table for loads completed within the last week.", "sanitized_sql": "SELECT TOP (500) SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())\n AND DateOut < DATEADD(day, -6, SYSDATETIME())", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SUM(Tons) AS total_tons\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())\\n AND DateOut < DATEADD(day, -6, SYSDATETIME());\", \"summary\": \"The total tons of sugar hauled last week is calculated by summing the 'Tons' column from the 'dbo.SugarLoadData' table for loads completed within the last week.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:42:28.510363+00:00", "question": "How many total tons of sugar was hauled last week", "generated_sql": "SELECT SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())\n AND DateOut < DATEADD(day, -6, SYSDATETIME());", "summary": "The total tons of sugar hauled last week is calculated by summing the 'Tons' column from the 'dbo.SugarLoadData' table for loads completed within the last week.", "sanitized_sql": "SELECT TOP (500) SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())\n AND DateOut < DATEADD(day, -6, SYSDATETIME())", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-19T18:47:05.480865+00:00", "question": "How many total tons of sugar was hauled from 10/12 to 10/13", "generated_sql": "SELECT SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2023-10-12' AND DateOut < '2023-10-14';", "summary": "The total tons of sugar hauled from 10/12 to 10/13 is 20000 tons.", "sanitized_sql": "SELECT TOP (500) SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2023-10-12' AND DateOut < '2023-10-14'", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SUM(Tons) AS total_tons\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2023-10-12' AND DateOut < '2023-10-14';\", \"summary\": \"The total tons of sugar hauled from 10/12 to 10/13 is 20000 tons.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T18:47:55.327739+00:00", "question": "How many total tons of sugar was hauled from 10/12/25 to 10/13/25", "generated_sql": "SELECT SUM(\"Tons\") AS total_tons\n FROM dbo.SugarLoadData\n WHERE \"DateOut\" >= '2025-10-12 00:00:00' AND \"DateOut\" < '2025-10-14 00:00:00';", "summary": "The total tons of sugar hauled from 10/12/25 to 10/13/25 is calculated by summing the \"Tons\" column from the SugarLoadData table for the specified date range.", "sanitized_sql": "SELECT TOP (500) SUM(\"Tons\") AS total_tons\n FROM dbo.SugarLoadData\n WHERE \"DateOut\" >= '2025-10-12 00:00:00' AND \"DateOut\" < '2025-10-14 00:00:00'", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SUM(\\\"Tons\\\") AS total_tons\\n FROM dbo.SugarLoadData\\n WHERE \\\"DateOut\\\" >= '2025-10-12 00:00:00' AND \\\"DateOut\\\" < '2025-10-14 00:00:00';\", \"summary\": \"The total tons of sugar hauled from 10/12/25 to 10/13/25 is calculated by summing the \\\"Tons\\\" column from the SugarLoadData table for the specified date range.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": null}}
{"timestamp": "2025-10-19T19:15:38.910312+00:00", "question": "How many total tons of sugar was hauled from 10/12/25 to 10/13/25", "generated_sql": "SELECT SUM(\"Tons\") AS total_tons\n FROM dbo.SugarLoadData\n WHERE \"DateOut\" >= '2025-10-12 00:00:00' AND \"DateOut\" < '2025-10-14 00:00:00';", "summary": "The total tons of sugar hauled from 10/12/25 to 10/13/25 is calculated by summing the \"Tons\" column from the SugarLoadData table for the specified date range.", "sanitized_sql": "SELECT TOP (500) SUM(\"Tons\") AS total_tons\n FROM dbo.SugarLoadData\n WHERE \"DateOut\" >= '2025-10-12 00:00:00' AND \"DateOut\" < '2025-10-14 00:00:00'", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-19T19:33:45.535721+00:00", "question": "How many loads were hauled by biggawg yesterday", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%biggawg%')\n )\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "Biggawg hauled 0 loads yesterday.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%biggawg%')\n )\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (\\n SELECT VehicleId_Pk\\n FROM dbo.SugarVehicles\\n WHERE UPPER(TCompanyName) LIKE UPPER('%biggawg%')\\n )\\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(SYSDATETIME() AS date);\", \"summary\": \"Biggawg hauled 0 loads yesterday.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T19:33:58.013366+00:00", "question": "How many loads were hauled by bigdawg yesterday", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%'))\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "Bigdawg hauled 0 loads yesterday.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%'))\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%'))\\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(SYSDATETIME() AS date);\", \"summary\": \"Bigdawg hauled 0 loads yesterday.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T19:34:27.124384+00:00", "question": "List loads hauled by bigdawg yesterday", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "The SQL query lists all loads with the vehicle ID associated with 'BIGDAWG' from the previous day.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 6, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(SYSDATETIME() AS date);\", \"summary\": \"The SQL query lists all loads with the vehicle ID associated with 'BIGDAWG' from the previous day.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T19:34:57.968634+00:00", "question": "List loads hauled by bigdawg on 10/15/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%'))\n AND DateOut >= '2025-10-15 00:00:00'\n AND DateOut < '2025-10-16 00:00:00';", "summary": "The SQL query lists all loads that were hauled by vehicles associated with 'Bigdawg' on October 15, 2025.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%'))\n AND DateOut >= '2025-10-15 00:00:00'\n AND DateOut < '2025-10-16 00:00:00'", "row_count": 8, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%'))\\n AND DateOut >= '2025-10-15 00:00:00'\\n AND DateOut < '2025-10-16 00:00:00';\", \"summary\": \"The SQL query lists all loads that were hauled by vehicles associated with 'Bigdawg' on October 15, 2025.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T19:35:09.049248+00:00", "question": "List loads hauled by bigdawg on 10/15/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%'))\n AND DateOut >= '2025-10-15 00:00:00'\n AND DateOut < '2025-10-16 00:00:00';", "summary": "The SQL query lists all loads that were hauled by vehicles associated with 'Bigdawg' on October 15, 2025.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%'))\n AND DateOut >= '2025-10-15 00:00:00'\n AND DateOut < '2025-10-16 00:00:00'", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-19T23:06:51.113164+00:00", "question": "How many loads were hauled by csc", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%csc%');", "summary": "CSC hauled 0 loads.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%csc%')", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%csc%');\", \"summary\": \"CSC hauled 0 loads.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T23:06:57.297101+00:00", "question": "How many loads were hauled by csc", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%csc%');", "summary": "CSC hauled 0 loads.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%csc%')", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-19T23:07:16.856048+00:00", "question": "List loads hauled by csc", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\n FROM dbo.SugarLoadData\n WHERE UPPER(TCompanyName) LIKE UPPER('%csc%');", "summary": "The SQL query lists all loads that were hauled by a company named 'csc'.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\n FROM dbo.SugarLoadData\n WHERE UPPER(TCompanyName) LIKE UPPER('%csc%')", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\\n FROM dbo.SugarLoadData\\n WHERE UPPER(TCompanyName) LIKE UPPER('%csc%');\", \"summary\": \"The SQL query lists all loads that were hauled by a company named 'csc'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-19T23:07:25.306315+00:00", "question": "List loads hauled by csc", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\n FROM dbo.SugarLoadData\n WHERE UPPER(TCompanyName) LIKE UPPER('%csc%');", "summary": "The SQL query lists all loads that were hauled by a company named 'csc'.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\n FROM dbo.SugarLoadData\n WHERE UPPER(TCompanyName) LIKE UPPER('%csc%')", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T00:37:22.645566+00:00", "question": "List loads hauled by bigdawg", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n ORDER BY DateOut DESC;", "summary": "The SQL query lists all loads with the vehicle identifier associated with 'BIGDAWG' in descending order by exit time.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\n FROM dbo.SugarLoadData\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\n ORDER BY DateOut DESC", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\\n FROM dbo.SugarLoadData\\n WHERE VehicleId_Fk IN (SELECT VehicleId_Pk FROM dbo.SugarVehicles WHERE UPPER(TCompanyName) LIKE UPPER('%BIGDAWG%'))\\n ORDER BY DateOut DESC;\", \"summary\": \"The SQL query lists all loads with the vehicle identifier associated with 'BIGDAWG' in descending order by exit time.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["Dbo.sugarloaddata"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T01:27:37.500863+00:00", "question": "List all loads hauled yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "The SQL query lists all loads that were hauled yesterday, from 12 AM to 11:59 PM on the day before.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 20, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"The SQL query lists all loads that were hauled yesterday, from 12 AM to 11:59 PM on the day before.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T01:27:50.456575+00:00", "question": "List all loads hauled yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "The SQL query lists all loads that were hauled yesterday, from 12 AM to 11:59 PM on the day before.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T01:30:02.410255+00:00", "question": "How many loads hauled today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "There are currently 0 loads in transit.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\", \"summary\": \"There are currently 0 loads in transit.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T01:30:19.278920+00:00", "question": "List all loads hauled today", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "Retrieving all loads that were completed today.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 13, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\", \"summary\": \"Retrieving all loads that were completed today.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T02:53:09.414043+00:00", "question": "How mny loads were hauled by laca last week", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -14, SYSDATETIME())\n AND \"DateOut\" < DATEADD(day, -7, SYSDATETIME());", "summary": "Last week, LACA hauled 5 loads.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -14, SYSDATETIME())\n AND \"DateOut\" < DATEADD(day, -7, SYSDATETIME())", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\\n AND \\\"DateOut\\\" >= DATEADD(day, -14, SYSDATETIME())\\n AND \\\"DateOut\\\" < DATEADD(day, -7, SYSDATETIME());\", \"summary\": \"Last week, LACA hauled 5 loads.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T02:53:32.186844+00:00", "question": "list all loads hauled by laca last week", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < DATEADD(day, -6, SYSDATETIME());", "summary": "Retrieving all loads that were hauled by LACA in the last week.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < DATEADD(day, -6, SYSDATETIME())", "row_count": 10, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\\n AND \\\"DateOut\\\" >= DATEADD(day, -7, SYSDATETIME())\\n AND \\\"DateOut\\\" < DATEADD(day, -6, SYSDATETIME());\", \"summary\": \"Retrieving all loads that were hauled by LACA in the last week.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T02:53:51.365895+00:00", "question": "list all loads hauled by laca last week", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < DATEADD(day, -6, SYSDATETIME());", "summary": "Retrieving all loads that were hauled by LACA in the last week.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < DATEADD(day, -6, SYSDATETIME())", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T02:54:23.320016+00:00", "question": "list all loads hauled to barge", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([Destination]) LIKE UPPER('%Barge%');", "summary": "Retrieving all load data where the destination contains the word 'Barge'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([Destination]) LIKE UPPER('%Barge%')", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER([Destination]) LIKE UPPER('%Barge%');\", \"summary\": \"Retrieving all load data where the destination contains the word 'Barge'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T02:54:55.600886+00:00", "question": "list all loads hauled to barge", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([Destination]) LIKE UPPER('%Barge%');", "summary": "Retrieving all load data where the destination contains the word 'Barge'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([Destination]) LIKE UPPER('%Barge%')", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T02:59:40.468692+00:00", "question": "list all loads hauled from wh1 yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE LoadingLocation = 'WH1'\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "Retrieving all loads that were hauled from 'WH1' yesterday.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE LoadingLocation = 'WH1'\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE LoadingLocation = 'WH1'\\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(SYSDATETIME() AS date);\", \"summary\": \"Retrieving all loads that were hauled from 'WH1' yesterday.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:00:02.969395+00:00", "question": "list all loads hauled from WH1 yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE LoadingLocation = 'WH1'\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1;", "summary": "Retrieving all loads that were hauled from WH1 yesterday.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE LoadingLocation = 'WH1'\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE LoadingLocation = 'WH1'\\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1;\", \"summary\": \"Retrieving all loads that were hauled from WH1 yesterday.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:00:13.944824+00:00", "question": "list all loads hauled to WH1 yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"Destination\" = 'WH1'\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1;", "summary": "Retrieving all loads that were hauled to WH1 yesterday.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE \"Destination\" = 'WH1'\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE \\\"Destination\\\" = 'WH1'\\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1;\", \"summary\": \"Retrieving all loads that were hauled to WH1 yesterday.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:00:26.483832+00:00", "question": "list all loads hauled to port allen yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%port allen%')\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1;", "summary": "Retrieving all loads that were hauled to Port Allen yesterday.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%port allen%')\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER(Destination) LIKE UPPER('%port allen%')\\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1;\", \"summary\": \"Retrieving all loads that were hauled to Port Allen yesterday.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T03:00:50.974231+00:00", "question": "list all loads hauled to barge yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE Destination = 'Barge'\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all loads that were hauled to 'Barge' yesterday.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE Destination = 'Barge'\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 8, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE Destination = 'Barge'\\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"Retrieving all loads that were hauled to 'Barge' yesterday.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:01:27.937701+00:00", "question": "list all loads hauled to barge yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE Destination = 'Barge'\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all loads that were hauled to 'Barge' yesterday.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE Destination = 'Barge'\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T03:04:49.688897+00:00", "question": "list all loads hauled from wh1", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([LoadingLocation]) LIKE UPPER('%wh1%');", "summary": "Retrieving all load data where the loading location is 'wh1'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([LoadingLocation]) LIKE UPPER('%wh1%')", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER([LoadingLocation]) LIKE UPPER('%wh1%');\", \"summary\": \"Retrieving all load data where the loading location is 'wh1'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T03:05:31.176267+00:00", "question": "list all loads hauled from wh1 since sept 15th", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"LoadingLocation\" = 'WH1' AND \"DateIn\" >= '2023-09-15 00:00:00';", "summary": "All loads that were hauled from WH1 since September 15th are listed.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE \"LoadingLocation\" = 'WH1' AND \"DateIn\" >= '2023-09-15 00:00:00'", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE \\\"LoadingLocation\\\" = 'WH1' AND \\\"DateIn\\\" >= '2023-09-15 00:00:00';\", \"summary\": \"All loads that were hauled from WH1 since September 15th are listed.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:05:59.429513+00:00", "question": "list all loads hauled from wh1 since sept 15th", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"LoadingLocation\" = 'WH1' AND \"DateIn\" >= '2023-09-15 00:00:00';", "summary": "All loads that were hauled from WH1 since September 15th are listed.", "sanitized_sql": "SELECT TOP (1000) *\n FROM dbo.SugarLoadData\n WHERE \"LoadingLocation\" = 'WH1' AND \"DateIn\" >= '2023-09-15 00:00:00'", "row_count": 1000, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE \\\"LoadingLocation\\\" = 'WH1' AND \\\"DateIn\\\" >= '2023-09-15 00:00:00';\", \"summary\": \"All loads that were hauled from WH1 since September 15th are listed.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:06:49.388187+00:00", "question": "list all loads hauled from wh1 since 10/15/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"LoadingLocation\" = 'WH1' AND \"DateIn\" >= '2025-10-15 00:00:00';", "summary": "Retrieving all load data from the 'WH1' location since 10/15/2025.", "sanitized_sql": "SELECT TOP (1000) *\n FROM dbo.SugarLoadData\n WHERE \"LoadingLocation\" = 'WH1' AND \"DateIn\" >= '2025-10-15 00:00:00'", "row_count": 21, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE \\\"LoadingLocation\\\" = 'WH1' AND \\\"DateIn\\\" >= '2025-10-15 00:00:00';\", \"summary\": \"Retrieving all load data from the 'WH1' location since 10/15/2025.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:07:14.221279+00:00", "question": "list all loads hauled from wh1 since 9/15/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"LoadingLocation\" = 'WH1' AND \"DateIn\" >= '2025-09-15 00:00:00';", "summary": "Retrieving all load data from the 'WH1' location since September 15, 2025.", "sanitized_sql": "SELECT TOP (1000) *\n FROM dbo.SugarLoadData\n WHERE \"LoadingLocation\" = 'WH1' AND \"DateIn\" >= '2025-09-15 00:00:00'", "row_count": 414, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE \\\"LoadingLocation\\\" = 'WH1' AND \\\"DateIn\\\" >= '2025-09-15 00:00:00';\", \"summary\": \"Retrieving all load data from the 'WH1' location since September 15, 2025.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:08:02.204946+00:00", "question": "list all loads hauled from wh1 since 9/15/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE \"LoadingLocation\" = 'WH1' AND \"DateIn\" >= '2025-09-15 00:00:00';", "summary": "Retrieving all load data from the 'WH1' location since September 15, 2025.", "sanitized_sql": "SELECT TOP (1000) *\n FROM dbo.SugarLoadData\n WHERE \"LoadingLocation\" = 'WH1' AND \"DateIn\" >= '2025-09-15 00:00:00'", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T03:13:15.279246+00:00", "question": "how many loads hauled today", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "There are currently 0 loads in progress.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\", \"summary\": \"There are currently 0 loads in progress.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:13:29.611401+00:00", "question": "list all loads hauled today", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "Retrieving all loads that were hauled today.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)", "row_count": 14, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(SYSDATETIME() AS date);\", \"summary\": \"Retrieving all loads that were hauled today.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:15:10.786491+00:00", "question": "list all loads hauled today", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date);", "summary": "Retrieving all loads that were hauled today.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(SYSDATETIME() AS date)", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T03:18:21.263784+00:00", "question": "List all loads hauled on 10.13.25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE CAST(DateIn AS date) = '2025-10-13' OR CAST(DateOut AS date) = '2025-10-13';", "summary": "The SQL query lists all loads that were either weighed in or weighed out on 10.13.25.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE CAST(DateIn AS date) = '2025-10-13' OR CAST(DateOut AS date) = '2025-10-13'", "row_count": 44, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE CAST(DateIn AS date) = '2025-10-13' OR CAST(DateOut AS date) = '2025-10-13';\", \"summary\": \"The SQL query lists all loads that were either weighed in or weighed out on 10.13.25.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:21:17.549934+00:00", "question": "list all loads hauled yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all loads that were hauled yesterday from the SugarLoadData table.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 21, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"Retrieving all loads that were hauled yesterday from the SugarLoadData table.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:21:48.118837+00:00", "question": "list all loads hauled yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all loads that were hauled yesterday from the SugarLoadData table.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T03:24:15.883582+00:00", "question": "list loads hauled today", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\n FROM dbo.SugarLoadData\n WHERE DateIn >= CAST(SYSDATETIME() AS date)\n AND DateIn < DATEADD(day, 1, CAST(SYSDATETIME() AS date));", "summary": "The SQL query lists all loads that were hauled today, including their unique load ID, vehicle ID, trailer type, hauling company, driver ID, loading location, destination, time of entry, time of exit, scale weight, and gross weight.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\n FROM dbo.SugarLoadData\n WHERE DateIn >= CAST(SYSDATETIME() AS date)\n AND DateIn < DATEADD(day, 1, CAST(SYSDATETIME() AS date))", "row_count": 14, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\\n FROM dbo.SugarLoadData\\n WHERE DateIn >= CAST(SYSDATETIME() AS date)\\n AND DateIn < DATEADD(day, 1, CAST(SYSDATETIME() AS date));\", \"summary\": \"The SQL query lists all loads that were hauled today, including their unique load ID, vehicle ID, trailer type, hauling company, driver ID, loading location, destination, time of entry, time of exit, scale weight, and gross weight.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:26:44.878211+00:00", "question": "list all loads yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the previous 24 hours, which corresponds to yesterday's loads.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 21, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"Retrieving all load data from the previous 24 hours, which corresponds to yesterday's loads.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:28:28.074288+00:00", "question": "list all loads yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1;", "summary": "Retrieving all load data from the previous day.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1", "row_count": 7, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1;\", \"summary\": \"Retrieving all load data from the previous day.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:29:00.394655+00:00", "question": "list all loads hauled this month", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DATEPART(month, DateIn) = DATEPART(month, SYSDATETIME())\n AND DATEPART(year, DateIn) = DATEPART(year, SYSDATETIME());", "summary": "Retrieving all loads that occurred this month.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DATEPART(month, DateIn) = DATEPART(month, SYSDATETIME())\n AND DATEPART(year, DateIn) = DATEPART(year, SYSDATETIME())", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DATEPART(month, DateIn) = DATEPART(month, SYSDATETIME())\\n AND DATEPART(year, DateIn) = DATEPART(year, SYSDATETIME());\", \"summary\": \"Retrieving all loads that occurred this month.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T03:30:02.549022+00:00", "question": "list all loads hauled to barge this month", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEFROMPARTS(YEAR(SYSDATETIME()), MONTH(SYSDATETIME()), 1)\n AND DateOut < DATEFROMPARTS(YEAR(SYSDATETIME()), MONTH(SYSDATETIME()) + 1, 1);", "summary": "Retrieving all load data for loads hauled to barge this month.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEFROMPARTS(YEAR(SYSDATETIME()), MONTH(SYSDATETIME()), 1)\n AND DateOut < DATEFROMPARTS(YEAR(SYSDATETIME()), MONTH(SYSDATETIME()) + 1, 1)", "row_count": 91, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\\n AND DateOut >= DATEFROMPARTS(YEAR(SYSDATETIME()), MONTH(SYSDATETIME()), 1)\\n AND DateOut < DATEFROMPARTS(YEAR(SYSDATETIME()), MONTH(SYSDATETIME()) + 1, 1);\", \"summary\": \"Retrieving all load data for loads hauled to barge this month.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T03:30:20.194423+00:00", "question": "list all loads hauled to barge this month", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEFROMPARTS(YEAR(SYSDATETIME()), MONTH(SYSDATETIME()), 1)\n AND DateOut < DATEFROMPARTS(YEAR(SYSDATETIME()), MONTH(SYSDATETIME()) + 1, 1);", "summary": "Retrieving all load data for loads hauled to barge this month.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEFROMPARTS(YEAR(SYSDATETIME()), MONTH(SYSDATETIME()), 1)\n AND DateOut < DATEFROMPARTS(YEAR(SYSDATETIME()), MONTH(SYSDATETIME()) + 1, 1)", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T03:30:41.861220+00:00", "question": "list all loads hauled to csc the past two months", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%CSC%')\n AND DateOut >= DATEADD(month, -2, SYSDATETIME());", "summary": "Retrieving all loads that were hauled to CSC in the past two months.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%CSC%')\n AND DateOut >= DATEADD(month, -2, SYSDATETIME())", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER(Destination) LIKE UPPER('%CSC%')\\n AND DateOut >= DATEADD(month, -2, SYSDATETIME());\", \"summary\": \"Retrieving all loads that were hauled to CSC in the past two months.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T03:31:12.194287+00:00", "question": "list all loads hauled to lsr the past two months", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%LSR%')\n AND DateOut >= DATEADD(month, -2, SYSDATETIME());", "summary": "Retrieving all loads that were hauled to LSR in the past two months.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%LSR%')\n AND DateOut >= DATEADD(month, -2, SYSDATETIME())", "row_count": 318, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER(Destination) LIKE UPPER('%LSR%')\\n AND DateOut >= DATEADD(month, -2, SYSDATETIME());\", \"summary\": \"Retrieving all loads that were hauled to LSR in the past two months.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:08:37.369732+00:00", "question": "list the loads from yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 36, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T13:09:11.755685+00:00", "question": "list the loads from yesterday that had a tare of less that 30000", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\n FROM dbo.SugarLoadData\n WHERE DateIn >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateIn < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1\n AND TareWt < 30000;", "summary": "The SQL query lists all loads from yesterday that had a tare weight less than 30000.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\n FROM dbo.SugarLoadData\n WHERE DateIn >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateIn < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1\n AND TareWt < 30000", "row_count": 2, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\\n FROM dbo.SugarLoadData\\n WHERE DateIn >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateIn < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1\\n AND TareWt < 30000;\", \"summary\": \"The SQL query lists all loads from yesterday that had a tare weight less than 30000.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T13:09:16.517280+00:00", "question": "list the loads from yesterday that had a tare of less that 30000", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\n FROM dbo.SugarLoadData\n WHERE DateIn >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateIn < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1\n AND TareWt < 30000;", "summary": "The SQL query lists all loads from yesterday that had a tare weight less than 30000.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\n FROM dbo.SugarLoadData\n WHERE DateIn >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateIn < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1\n AND TareWt < 30000", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T13:09:29.513624+00:00", "question": "list the loads from yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 36, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T13:09:29.514205+00:00", "question": "list the loads from yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 36, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T13:09:33.291431+00:00", "question": "list the loads from yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T13:10:06.924286+00:00", "question": "list the loads from yesterday that were hauled to barge", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "The SQL query lists all loads from yesterday that were hauled to a barge.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 18, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\\n FROM dbo.SugarLoadData\\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"The SQL query lists all loads from yesterday that were hauled to a barge.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:10:28.726357+00:00", "question": "list the loads from yesterday that were hauled to barge", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "The SQL query lists all loads from yesterday that were hauled to a barge.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, TrailerTypeID, TCompanyName, DriverID, LoadingLocation, Destination, DateIn, DateOut, ScaleWT, GrossWt, TareWt\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T13:10:52.695953+00:00", "question": "list the loads from yesterday that were hauled to csc", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1\n AND UPPER(Destination) LIKE UPPER('%CSC%');", "summary": "The SQL query lists all loads from yesterday that were hauled to CSC.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1\n AND UPPER(Destination) LIKE UPPER('%CSC%')", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 1\\n AND UPPER(Destination) LIKE UPPER('%CSC%');\", \"summary\": \"The SQL query lists all loads from yesterday that were hauled to CSC.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:11:02.077718+00:00", "question": "list the loads from yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 36, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T13:11:59.018065+00:00", "question": "list the loads from yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T13:12:53.026029+00:00", "question": "how many loads were hauled on 10/13/25", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00';", "summary": "There were 0 loads hauled on 10/13/25.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00'", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-13 00:00:00'\\n AND DateOut < '2025-10-14 00:00:00';\", \"summary\": \"There were 0 loads hauled on 10/13/25.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T13:13:00.718366+00:00", "question": "list loads were hauled on 10/13/25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateIn >= '2025-10-13 00:00:00' AND DateIn < '2025-10-14 00:00:00';", "summary": "The SQL query lists all loads that were hauled on October 13, 2025.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateIn >= '2025-10-13 00:00:00' AND DateIn < '2025-10-14 00:00:00'", "row_count": 44, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateIn >= '2025-10-13 00:00:00' AND DateIn < '2025-10-14 00:00:00';\", \"summary\": \"The SQL query lists all loads that were hauled on October 13, 2025.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T13:13:20.630341+00:00", "question": "list loads were hauled on 10/13/25 hauled by laca", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%LACA%');", "summary": "The SQL query lists all loads that were hauled on October 13, 2025, by the company 'LACA'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%LACA%')", "row_count": 10, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-13 00:00:00'\\n AND DateOut < '2025-10-14 00:00:00'\\n AND UPPER(TCompanyName) LIKE UPPER('%LACA%');\", \"summary\": \"The SQL query lists all loads that were hauled on October 13, 2025, by the company 'LACA'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:13:39.353392+00:00", "question": "list loads were hauled on 10/13/25 hauled by bigdawg", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%Bigdawg%');", "summary": "The SQL query lists all loads that were completed on October 13, 2025, and were hauled by a company named 'Bigdawg'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00'\n AND UPPER(TCompanyName) LIKE UPPER('%Bigdawg%')", "row_count": 9, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-13 00:00:00'\\n AND DateOut < '2025-10-14 00:00:00'\\n AND UPPER(TCompanyName) LIKE UPPER('%Bigdawg%');\", \"summary\": \"The SQL query lists all loads that were completed on October 13, 2025, and were hauled by a company named 'Bigdawg'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:14:07.130590+00:00", "question": "list loads were hauled on 10/13/25 hauled by bigdawg that were over 95000", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, DateOut\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00'\n AND VehicleId_Fk = 'BIGDAWG'\n AND GrossWt > 95000;", "summary": "The SQL query lists loads that were hauled by 'BIGDAWG' on 10/13/25 with a gross weight over 95000.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, DateOut\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00'\n AND VehicleId_Fk = 'BIGDAWG'\n AND GrossWt > 95000", "row_count": 0, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, DateOut\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-13 00:00:00'\\n AND DateOut < '2025-10-14 00:00:00'\\n AND VehicleId_Fk = 'BIGDAWG'\\n AND GrossWt > 95000;\", \"summary\": \"The SQL query lists loads that were hauled by 'BIGDAWG' on 10/13/25 with a gross weight over 95000.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T13:15:02.519889+00:00", "question": "list loads were hauled on 10/13/25 hauled by bigdawg that had a gross over 93000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\n )\n AND GrossWt > 93000;", "summary": "The SQL query lists all loads that were hauled on October 13, 2025, by vehicles associated with 'BigDawg', and had a gross weight over 93000.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\n )\n AND GrossWt > 93000", "row_count": 6, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-13 00:00:00'\\n AND DateOut < '2025-10-14 00:00:00'\\n AND VehicleId_Fk IN (\\n SELECT VehicleId_Pk\\n FROM dbo.SugarVehicles\\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\\n )\\n AND GrossWt > 93000;\", \"summary\": \"The SQL query lists all loads that were hauled on October 13, 2025, by vehicles associated with 'BigDawg', and had a gross weight over 93000.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:15:33.521323+00:00", "question": "list loads were hauled on 10/13/25 hauled by bigdawg that had a gross over 93000 and total the tons", "generated_sql": "SELECT COUNT(*) AS load_count, SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\n )\n AND GrossWt > 93000;", "summary": "There were 2 loads hauled by Bigdawg on 10/13/25 with a gross weight over 93000, totaling 10 tons.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count, SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-13 00:00:00'\n AND DateOut < '2025-10-14 00:00:00'\n AND VehicleId_Fk IN (\n SELECT VehicleId_Pk\n FROM dbo.SugarVehicles\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\n )\n AND GrossWt > 93000", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count, SUM(Tons) AS total_tons\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-13 00:00:00'\\n AND DateOut < '2025-10-14 00:00:00'\\n AND VehicleId_Fk IN (\\n SELECT VehicleId_Pk\\n FROM dbo.SugarVehicles\\n WHERE UPPER(TCompanyName) LIKE UPPER('%bigdawg%')\\n )\\n AND GrossWt > 93000;\", \"summary\": \"There were 2 loads hauled by Bigdawg on 10/13/25 with a gross weight over 93000, totaling 10 tons.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:34:23.791580+00:00", "question": "How many loads were hauled by laca", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%');", "summary": "", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%')", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%');\", \"summary\": \"\", \"llm_warning\": \"Postprocess: Removed unrequested date/time filters from SQL output.; Attempt 1: Model response did not include a valid SELECT statement.; Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Removed unrequested date/time filters from SQL output.; Attempt 1: Model response did not include a valid SELECT statement.; Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:34:42.273419+00:00", "question": "How many loads were hauled by laca and the destination was csc", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%') AND UPPER([Destination]) LIKE UPPER('%csc%');", "summary": "There were 0 loads hauled by LACA and the destination was CSC.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%') AND UPPER([Destination]) LIKE UPPER('%csc%')", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%') AND UPPER([Destination]) LIKE UPPER('%csc%');\", \"summary\": \"There were 0 loads hauled by LACA and the destination was CSC.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:34:50.660739+00:00", "question": "How many loads were hauled by laca and the destination was barge", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%') AND UPPER([Destination]) LIKE UPPER('%barge%');", "summary": "There were 0 loads hauled by LACA and the destination was Barge.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%') AND UPPER([Destination]) LIKE UPPER('%barge%')", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%') AND UPPER([Destination]) LIKE UPPER('%barge%');\", \"summary\": \"There were 0 loads hauled by LACA and the destination was Barge.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:35:20.907394+00:00", "question": "How many loads were hauled by laca and the destination was barge and had a gross over 100000", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%')\n AND UPPER([Destination]) LIKE UPPER('%barge%')\n AND \"GrossWt\" > 100000;", "summary": "There were 0 loads hauled by LACA and destined for BARGE with a gross weight over 100000.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%')\n AND UPPER([Destination]) LIKE UPPER('%barge%')\n AND \"GrossWt\" > 100000", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%laca%')\\n AND UPPER([Destination]) LIKE UPPER('%barge%')\\n AND \\\"GrossWt\\\" > 100000;\", \"summary\": \"There were 0 loads hauled by LACA and destined for BARGE with a gross weight over 100000.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:35:36.328365+00:00", "question": "list loads hauled by laca and the destination was barge and had a gross over 100000", "generated_sql": "SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND UPPER([Destination]) LIKE UPPER('%Barge%')\n AND \"GrossWt\" > 100000;", "summary": "Here are the load IDs, vehicle IDs, gross weights, tare weights, and tons for loads hauled by LACA to a destination of Barge with a gross weight over 100000.", "sanitized_sql": "SELECT TOP (500) SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND UPPER([Destination]) LIKE UPPER('%Barge%')\n AND \"GrossWt\" > 100000", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SugarLoadID_Pk, VehicleId_Fk, GrossWt, TareWt, Tons, DateOut\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\\n AND UPPER([Destination]) LIKE UPPER('%Barge%')\\n AND \\\"GrossWt\\\" > 100000;\", \"summary\": \"Here are the load IDs, vehicle IDs, gross weights, tare weights, and tons for loads hauled by LACA to a destination of Barge with a gross weight over 100000.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:37:06.295563+00:00", "question": "list all the loads hauled by bigdawg", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%bigdawg%');", "summary": "Here is a list of all loads hauled by 'Bigdawg'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%bigdawg%')", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%bigdawg%');\", \"summary\": \"Here is a list of all loads hauled by 'Bigdawg'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:37:25.783588+00:00", "question": "list all the loads hauled by bigdawg that had a gross over 100000", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%BIGDAWG%') AND \"GrossWt\" > 100000;", "summary": "Bigdawg has hauled 100000+ gross loads.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%BIGDAWG%') AND \"GrossWt\" > 100000", "row_count": 244, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%BIGDAWG%') AND \\\"GrossWt\\\" > 100000;\", \"summary\": \"Bigdawg has hauled 100000+ gross loads.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T13:37:43.576019+00:00", "question": "list all the loads hauled by bigdawg that had a gross over 100000 and went to baldwin", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%bigdawg%')\n AND \"GrossWt\" > 100000\n AND UPPER([Destination]) LIKE UPPER('%baldwin%');", "summary": "Bigdawg has hauled loads with a gross weight over 100000 that went to baldwin.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%bigdawg%')\n AND \"GrossWt\" > 100000\n AND UPPER([Destination]) LIKE UPPER('%baldwin%')", "row_count": 21, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%bigdawg%')\\n AND \\\"GrossWt\\\" > 100000\\n AND UPPER([Destination]) LIKE UPPER('%baldwin%');\", \"summary\": \"Bigdawg has hauled loads with a gross weight over 100000 that went to baldwin.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T14:03:27.329984+00:00", "question": "list all loads from yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 42, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T14:06:15.440938+00:00", "question": "list all loads from 10-19-25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-19 00:00:00'\n AND DateOut < '2025-10-20 00:00:00';", "summary": "", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-19 00:00:00'\n AND DateOut < '2025-10-20 00:00:00'", "row_count": 15, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-19 00:00:00'\\n AND DateOut < '2025-10-20 00:00:00';\", \"summary\": \"\", \"llm_warning\": \"Attempt 1: Model response did not include a valid SELECT statement.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Attempt 1: Model response did not include a valid SELECT statement."}}
{"timestamp": "2025-10-20T14:07:20.852836+00:00", "question": "list all loads from 10-19-25", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-19 00:00:00'\n AND DateOut < '2025-10-20 00:00:00';", "summary": "", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-19 00:00:00'\n AND DateOut < '2025-10-20 00:00:00'", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T14:48:46.730407+00:00", "question": "how many loads yesterday", "generated_sql": "SELECT COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date);", "summary": "There were 0 loads yesterday.", "sanitized_sql": "SELECT TOP (500) COUNT(*) AS load_count\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(SYSDATETIME() AS date)", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT COUNT(*) AS load_count\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(SYSDATETIME() AS date);\", \"summary\": \"There were 0 loads yesterday.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T14:49:05.697218+00:00", "question": "list all loads yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 49, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T14:49:09.881931+00:00", "question": "list all loads yesterday", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "Retrieving all load data from the SugarLoadData table for the 24 hours preceding yesterday's end time.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}
{"timestamp": "2025-10-20T15:02:55.244937+00:00", "question": "Show all loads hauled by csc", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%csc%');", "summary": "Retrieving all load data for loads hauled by 'CSC'.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%csc%')", "row_count": 500, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%csc%');\", \"summary\": \"Retrieving all load data for loads hauled by 'CSC'.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T15:03:20.873801+00:00", "question": "Show all loads hauled by csc last week", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%csc%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < DATEADD(day, -6, SYSDATETIME());", "summary": "Retrieving all loads that were hauled by CSC in the last week.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%csc%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < DATEADD(day, -6, SYSDATETIME())", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%csc%')\\n AND \\\"DateOut\\\" >= DATEADD(day, -7, SYSDATETIME())\\n AND \\\"DateOut\\\" < DATEADD(day, -6, SYSDATETIME());\", \"summary\": \"Retrieving all loads that were hauled by CSC in the last week.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T15:04:05.686501+00:00", "question": "Show all loads hauled to barge this week", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\n AND DateOut < DATEADD(week, 1, SYSDATETIME());", "summary": "All loads that were hauled to a destination containing 'Barge' and completed within the last week are displayed.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\n AND DateOut < DATEADD(week, 1, SYSDATETIME())", "row_count": 28, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\\n AND DateOut < DATEADD(week, 1, SYSDATETIME());\", \"summary\": \"All loads that were hauled to a destination containing 'Barge' and completed within the last week are displayed.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T15:07:26.248232+00:00", "question": "Total tons hauled this week", "generated_sql": "SELECT SUM(Tons) AS total_tons_hauled\n FROM dbo.SugarLoadData\n WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())\n AND DateOut < SYSDATETIME();", "summary": "The total tons of sugar hauled this week is calculated by summing the 'Tons' column from the 'dbo.SugarLoadData' table for loads completed within the last 7 days.", "sanitized_sql": "SELECT TOP (500) SUM(Tons) AS total_tons_hauled\n FROM dbo.SugarLoadData\n WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())\n AND DateOut < SYSDATETIME()", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SUM(Tons) AS total_tons_hauled\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= DATEADD(day, -7, SYSDATETIME())\\n AND DateOut < SYSDATETIME();\", \"summary\": \"The total tons of sugar hauled this week is calculated by summing the 'Tons' column from the 'dbo.SugarLoadData' table for loads completed within the last 7 days.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T15:07:55.064127+00:00", "question": "Total tons hauled on 10/14/25", "generated_sql": "SELECT SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00';", "summary": "The total tons of sugar hauled on October 14, 2025, is calculated by summing the \"Tons\" column for loads that exited on that date.", "sanitized_sql": "SELECT TOP (500) SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SUM(Tons) AS total_tons\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-14 00:00:00'\\n AND DateOut < '2025-10-15 00:00:00';\", \"summary\": \"The total tons of sugar hauled on October 14, 2025, is calculated by summing the \\\"Tons\\\" column for loads that exited on that date.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T15:20:22.791466+00:00", "question": "Show all loads hauled by LACA this week", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < SYSDATETIME();", "summary": "All loads that were hauled by LACA and completed within the last week are being displayed.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < SYSDATETIME()", "row_count": 82, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\\n AND \\\"DateOut\\\" >= DATEADD(day, -7, SYSDATETIME())\\n AND \\\"DateOut\\\" < SYSDATETIME();\", \"summary\": \"All loads that were hauled by LACA and completed within the last week are being displayed.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T15:20:35.071599+00:00", "question": "Show all loads hauled to barge this week.", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\n AND DateOut < DATEADD(week, 1, SYSDATETIME());", "summary": "", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\n AND DateOut < DATEADD(week, 1, SYSDATETIME())", "row_count": 29, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\\n AND DateOut < DATEADD(week, 1, SYSDATETIME());\", \"summary\": \"\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T15:20:47.072709+00:00", "question": "List all loads from yesterday.", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;", "summary": "", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24", "row_count": 54, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime)\\n AND DateOut < CAST(DATEADD(day, -1, CAST(SYSDATETIME() AS date)) AS datetime) + 24;\", \"summary\": \"\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T15:21:12.658850+00:00", "question": "Total tons hauled on 10/14/25", "generated_sql": "SELECT SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00';", "summary": "The total tons hauled on October 14, 2025, is calculated by summing the \"Tons\" column for loads that exited on that date.", "sanitized_sql": "SELECT TOP (500) SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SUM(Tons) AS total_tons\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-14 00:00:00'\\n AND DateOut < '2025-10-15 00:00:00';\", \"summary\": \"The total tons hauled on October 14, 2025, is calculated by summing the \\\"Tons\\\" column for loads that exited on that date.\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T15:36:46.030462+00:00", "question": "Show all loads hauled by LACA this week", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < SYSDATETIME();", "summary": "LACA has hauled 7 days worth of loads from the last week.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < SYSDATETIME()", "row_count": 83, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\\n AND \\\"DateOut\\\" >= DATEADD(day, -7, SYSDATETIME())\\n AND \\\"DateOut\\\" < SYSDATETIME();\", \"summary\": \"LACA has hauled 7 days worth of loads from the last week.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T15:36:55.616260+00:00", "question": "Show all loads hauled by LACA last week", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < DATEADD(day, -6, SYSDATETIME());", "summary": "Retrieving all loads that were hauled by LACA in the last week.", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\n AND \"DateOut\" >= DATEADD(day, -7, SYSDATETIME())\n AND \"DateOut\" < DATEADD(day, -6, SYSDATETIME())", "row_count": 16, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER([TCompanyName]) LIKE UPPER('%LACA%')\\n AND \\\"DateOut\\\" >= DATEADD(day, -7, SYSDATETIME())\\n AND \\\"DateOut\\\" < DATEADD(day, -6, SYSDATETIME());\", \"summary\": \"Retrieving all loads that were hauled by LACA in the last week.\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T15:40:28.042926+00:00", "question": "Show all loads hauled to barge this week.", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\n AND DateOut < DATEADD(week, 1, SYSDATETIME());", "summary": "", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\n AND DateOut < DATEADD(week, 1, SYSDATETIME())", "row_count": 31, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\\n AND DateOut < DATEADD(week, 1, SYSDATETIME());\", \"summary\": \"\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T15:46:41.297995+00:00", "question": "Show all loads hauled to barge this week.", "generated_sql": "SELECT *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\n AND DateOut < DATEADD(week, 1, SYSDATETIME());", "summary": "", "sanitized_sql": "SELECT TOP (500) *\n FROM dbo.SugarLoadData\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\n AND DateOut < DATEADD(week, 1, SYSDATETIME())", "row_count": 32, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT *\\n FROM dbo.SugarLoadData\\n WHERE UPPER(Destination) LIKE UPPER('%Barge%')\\n AND DateOut >= DATEADD(week, -1, SYSDATETIME())\\n AND DateOut < DATEADD(week, 1, SYSDATETIME());\", \"summary\": \"\", \"llm_warning\": \"Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE).\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": "Postprocess: Normalized syntax to SQL Server equivalents (e.g., LIKE)."}}
{"timestamp": "2025-10-20T15:47:12.848496+00:00", "question": "Total tons hauled on 10/14/25.", "generated_sql": "SELECT SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00';", "summary": "", "sanitized_sql": "SELECT TOP (500) SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'", "row_count": 1, "execution_status": "success", "raw_response": "{\"sql\": \"SELECT SUM(Tons) AS total_tons\\n FROM dbo.SugarLoadData\\n WHERE DateOut >= '2025-10-14 00:00:00'\\n AND DateOut < '2025-10-15 00:00:00';\", \"summary\": \"\"}", "metadata": {"source": "ui", "execute": true, "tables": ["dbo.SugarLoadData"], "llm_warning": null}}
{"timestamp": "2025-10-20T15:47:16.972729+00:00", "question": "Total tons hauled on 10/14/25.", "generated_sql": "SELECT SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00';", "summary": "", "sanitized_sql": "SELECT TOP (500) SUM(Tons) AS total_tons\n FROM dbo.SugarLoadData\n WHERE DateOut >= '2025-10-14 00:00:00'\n AND DateOut < '2025-10-15 00:00:00'", "user_feedback": "correct", "metadata": {"source": "ui-feedback", "feedback_only": true}}

View File

@@ -0,0 +1,33 @@
# Prompt Assembly
Utilities for packaging database context into a single LLM prompt.
## Files
- `prompt_builder.py`: Loads schema/glossary/value hints/example artifacts and produces a structured prompt for SQL generation.
- `__init__.py`: Exposes `load_context` and `build_prompt` helpers.
## Quick Start
1. Ensure context artifacts exist under `db_agent/context/` (run the extractor, curate glossary/value hints/examples).
2. In Python, build the prompt:
```python
from db_agent.prompting import load_context, build_prompt
ctx = load_context()
prompt = build_prompt(
question="Which vehicles hauled more than 30 tons last week?",
context=ctx,
table_hints=["dbo.SugarLoadData", "dbo.SugarVehicles"],
)
print(prompt)
```
3. Send the prompt to your LLM provider (OpenAI, Azure OpenAI, Anthropic, etc.) and parse the JSON response with the `sql` and `summary` fields.
## Configuration
- Customize file paths by instantiating `PromptConfig` with alternate filenames or directories.
- Use `table_hints` to restrict the schema section to relevant tables (helps stay within context limits).
- Adjust `max_columns` to control how many column definitions are emitted per table.
## Next Steps
- Integrate the prompt builder into a service layer that calls the LLM and executes the generated SQL with validation.
- Add retrieval heuristics to automatically pick tables based on keyword matching instead of manually passing `table_hints`.
- Extend the format to include recent query logs or execution feedback for reinforcement.

View File

@@ -0,0 +1,10 @@
"""Prompt assembly utilities for the database agent."""
from .prompt_builder import AgentContext, PromptConfig, build_prompt, load_context
__all__ = [
"AgentContext",
"PromptConfig",
"build_prompt",
"load_context",
]

View File

@@ -0,0 +1,190 @@
"""Assemble LLM prompts for natural-language SQL generation."""
from __future__ import annotations
import json
import textwrap
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Sequence
import yaml
@dataclass(frozen=True)
class PromptConfig:
"""File layout for context artifacts consumed by the prompt builder."""
context_dir: Path = field(default_factory=lambda: Path("db_agent/context"))
schema_filename: str = "schema.json"
glossary_filename: str = "glossary.md"
value_hints_filename: str = "value_hints.yaml"
examples_filename: str = "examples.json"
@dataclass
class AgentContext:
"""Loaded context assets ready for prompt rendering."""
schema: Dict[str, Any]
glossary_markdown: str
value_hints: Dict[str, Any]
examples: List[Dict[str, Any]]
def load_context(config: PromptConfig | None = None) -> AgentContext:
"""Load the canonical context files from disk."""
cfg = config or PromptConfig()
base = cfg.context_dir
schema_path = base / cfg.schema_filename
glossary_path = base / cfg.glossary_filename
value_hints_path = base / cfg.value_hints_filename
examples_path = base / cfg.examples_filename
schema = json.loads(schema_path.read_text(encoding="utf-8"))
glossary_markdown = glossary_path.read_text(encoding="utf-8")
value_hints = yaml.safe_load(value_hints_path.read_text(encoding="utf-8")) or {}
examples = json.loads(examples_path.read_text(encoding="utf-8"))
return AgentContext(
schema=schema,
glossary_markdown=glossary_markdown,
value_hints=value_hints,
examples=examples,
)
def _format_table(table_key: str, table_doc: Dict[str, Any], max_columns: int) -> str:
"""Render a single table definition block."""
lines: List[str] = [f"Table {table_key}: {table_doc.get('schema')}.{table_doc.get('name')}"]
column_docs = table_doc.get("columns", [])
for idx, column in enumerate(column_docs):
if idx >= max_columns:
lines.append(f" ... ({len(column_docs) - max_columns} more columns omitted)")
break
col_line = f" - {column['name']} ({column['type']})"
if column.get("nullable") is False:
col_line += " NOT NULL"
if column.get("default") not in (None, ""):
col_line += f" DEFAULT {column['default']}"
lines.append(col_line)
relationships = table_doc.get("relationships", [])
if relationships:
lines.append(" Relationships:")
for rel in relationships:
target = rel.get("target")
src_col = rel.get("source_column")
tgt_col = rel.get("target_column")
lines.append(f" * {src_col} -> {target}.{tgt_col}")
return "\n".join(lines)
def _format_schema(schema_doc: Dict[str, Any], include_tables: Optional[Sequence[str]], max_columns: int) -> str:
"""Render the subset of tables to include in the prompt."""
table_section: List[str] = []
tables = schema_doc.get("tables", {})
def table_selected(table_key: str, table_doc: Dict[str, Any]) -> bool:
if not include_tables:
return True
candidates = {table_key, table_doc.get("name"), f"{table_doc.get('schema')}.{table_doc.get('name')}"}
return any(name in include_tables for name in candidates if name)
for table_key, table_doc in tables.items():
if table_selected(table_key, table_doc):
table_section.append(_format_table(table_key, table_doc, max_columns=max_columns))
if not table_section:
return "(No tables selected; broaden include_tables to see schema context.)"
return "\n\n".join(table_section)
def _format_examples(examples: Iterable[Dict[str, Any]]) -> str:
"""Render examples as numbered items for clarity."""
lines: List[str] = []
for idx, example in enumerate(examples, start=1):
question = example.get("question", "(missing question)")
sql = example.get("sql", "-- SQL not provided")
notes = example.get("notes")
lines.append(f"Example {idx}: {question}")
lines.append("SQL:\n" + sql)
if notes:
lines.append(f"Notes: {notes}")
lines.append("")
return "\n".join(lines).strip()
def _format_value_hints(hints: Dict[str, Any]) -> str:
"""Dump value hints to YAML for prompt readability."""
if not hints:
return "(No value hints available.)"
return yaml.safe_dump(hints, sort_keys=False, allow_unicode=False)
def build_prompt(
question: str,
context: AgentContext,
table_hints: Optional[Sequence[str]] = None,
max_columns: int = 12,
format_hint: Optional[str] = None,
) -> str:
"""Compose the full system + user prompt for the SQL agent."""
schema_section = _format_schema(context.schema, include_tables=table_hints, max_columns=max_columns)
examples_section = _format_examples(context.examples)
value_hints_section = _format_value_hints(context.value_hints)
additional_instructions = ""
if format_hint:
additional_instructions = f"\n ### Additional Formatting Instructions\n {format_hint}\n"
prompt = textwrap.dedent(
f"""You are an assistant that translates operator questions into safe T-SQL for SQL Server.
Follow these rules:
- Use SELECT statements only; never modify data.
- Apply TOP or date filters only when explicitly requested or when needed to respect the max_rows limit; never infer time windows that the user did not mention.
- Reference fully qualified table names with schema (e.g., dbo.TableName).
- Use SQL Server date/time functions: prefer CONVERT(date, ...), CAST(... AS date), DATEPART, DATEADD, DATEDIFF. Do not use MySQL/Postgres functions like DATE(), EXTRACT(), or INTERVAL literals.
- Stick to SQL Server syntax: use LIKE (and optionally UPPER/LTRIM/RTRIM) instead of ILIKE; avoid LIMIT/OFFSET, NULLS FIRST/LAST, USING, or other non-T-SQL constructs.
- Only include literals or filters grounded in the question or provided hints; do not fabricate IDs, random suffixes, or placeholder strings.
- Every filter must be justified by the user question: "{question}". If the question does not reference a timeframe, do not add one. If unsure, return an empty sql value and ask for clarification in the summary.
- If information is missing, ask for clarification instead of guessing.
### Database Schema
{schema_section}
### Business Glossary
{context.glossary_markdown.strip()}
### Value Hints
{value_hints_section.strip()}
### Worked Examples
{examples_section}
### Task
Generate a SQL query that answers the user question and summarize the answer in natural language.
Return ONLY a JSON object with the following structure (no code fences, no extra commentary):
{{"sql": "<the SQL query>", "summary": "<one sentence summary>"}}
{additional_instructions}
User question: {question}
"""
).strip()
return prompt
__all__ = [
"PromptConfig",
"AgentContext",
"load_context",
"build_prompt",
]

View File

@@ -0,0 +1,7 @@
sqlalchemy>=2.0,<3.0
pyodbc>=5.0,<6.0
PyYAML>=6.0,<7.0
requests>=2.31,<3.0
urllib3>=1.26,<2.0
fastapi>=0.111,<1.0
uvicorn[standard]>=0.30,<1.0

View File

@@ -0,0 +1,140 @@
"""Example entry point for running a natural-language SQL query."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
from typing import Optional
from .client import SqlAgentClient, default_client
from .log_utils import log_interaction
from .sql_executor import SqlExecutionResult, SqlValidationError, execute_sql
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Run a question through the SQL agent.")
parser.add_argument("question", help="Natural language question to transform into SQL.")
parser.add_argument(
"--tables",
nargs="*",
default=None,
help="Optional list of tables to prioritize (e.g., dbo.SugarLoadData).",
)
parser.add_argument(
"--output",
type=str,
default=None,
help="Optional path to write the raw LLM JSON response.",
)
parser.add_argument(
"--execute",
action="store_true",
help="Validate and run the generated SQL against MSSQL.",
)
parser.add_argument(
"--max-rows",
type=int,
default=500,
help="Maximum rows to fetch; enforced via TOP clause when executing.",
)
parser.add_argument(
"--log-path",
type=str,
default=None,
help="Append interaction logs to this JSONL file (defaults to db_agent/logs/query_log.jsonl).",
)
parser.add_argument(
"--no-log",
action="store_true",
help="Disable interaction logging.",
)
return parser.parse_args()
def main() -> None:
args = parse_args()
client: SqlAgentClient = default_client()
response = client.query(question=args.question, table_hints=args.tables)
if args.output:
with open(args.output, "w", encoding="utf-8") as fp:
json.dump(response, fp, indent=2)
print(f"Response written to {args.output}")
else:
print(json.dumps(response, indent=2))
generated_sql = response.get("sql", "").strip()
summary = response.get("summary", "").strip()
execution_result: Optional[SqlExecutionResult] = None
normalized_sql = generated_sql.lstrip()
sql_is_select = normalized_sql.lower().startswith("select") if normalized_sql else False
execution_warning: Optional[str] = None
execution_status: Optional[str] = None
execution_error: Optional[str] = None
if args.execute:
if not normalized_sql:
execution_warning = "No SQL returned; skipping execution."
print(execution_warning)
elif not sql_is_select:
execution_warning = "Generated SQL is not a SELECT statement; skipping execution."
print(execution_warning)
else:
try:
execution_result = execute_sql(normalized_sql, max_rows=args.max_rows)
except SqlValidationError as exc:
execution_warning = f"SQL validation failed: {exc}"
execution_error = str(exc)
print(f"SQL validation failed: {exc}")
except Exception as exc:
execution_error = str(exc)
print(f"SQL execution failed: {exc}")
raise
else:
execution_status = "success"
print("Sanitized SQL:")
print(execution_result.sql)
print(f"Rows returned: {len(execution_result.rows)}")
if execution_result.rows:
preview = execution_result.rows[: min(5, len(execution_result.rows))]
print("Preview (up to 5 rows):")
print(json.dumps(preview, indent=2, default=str))
if not args.no_log:
log_path = Path(args.log_path) if args.log_path else None
metadata = {
"tables_hint": args.tables,
"execution_requested": args.execute,
}
if execution_result:
metadata.update(
{
"columns": execution_result.columns,
"preview_rows": min(5, len(execution_result.rows)),
}
)
if execution_warning:
metadata["execution_warning"] = execution_warning
log_interaction(
question=args.question,
generated_sql=generated_sql,
summary=summary,
sanitized_sql=execution_result.sql if execution_result else None,
row_count=len(execution_result.rows) if execution_result else None,
execution_status=execution_status,
execution_error=execution_error,
raw_response=json.dumps(response, ensure_ascii=False),
log_path=log_path,
metadata=metadata,
)
if log_path:
print(f"Interaction appended to {log_path}")
else:
print("Interaction appended to db_agent/logs/query_log.jsonl")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,44 @@
# Requires dot-sourcing to persist variables in the current PowerShell session.
# Usage: `. .\db_agent\scripts\Set-DbEnv.ps1 -Server "SUGARSCALE\SQLEXPRESS" -Database "SugarScale_Lasuca" -Username "SugarAI" -Password (Read-Host -AsSecureString)`
# Never commit real credentials.
param(
[string]$Server = "SUGARSCALE\SQLEXPRESS",
[string]$Database = "SugarScale_Lasuca",
[string]$Username = "SugarAI",
[SecureString]$Password,
[string]$Driver = "ODBC Driver 17 for SQL Server",
[bool]$Encrypt = $true,
[bool]$TrustCertificate = $true
)
function Convert-SecureStringToPlainText {
param([SecureString]$SecureString)
if (-not $SecureString) {
return $null
}
$ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecureString)
try {
return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr)
}
finally {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr)
}
}
if (-not $Password) {
$Password = Read-Host -Prompt "Enter DB password" -AsSecureString
}
$plainPassword = Convert-SecureStringToPlainText -SecureString $Password
if (-not $plainPassword) {
throw "Password is required. Provide -Password (Read-Host -AsSecureString)."}
$env:DB_SERVER = $Server
$env:DB_DATABASE = $Database
$env:DB_USERNAME = $Username
$env:DB_PASSWORD = $plainPassword
$env:DB_DRIVER = $Driver
$env:DB_ENCRYPT = $Encrypt.ToString().ToLower()
$env:DB_TRUST_CERT = $TrustCertificate.ToString().ToLower()
Write-Host "DB env vars set for this session."

View File

@@ -0,0 +1,140 @@
"""Validation and execution helpers for generated SQL queries."""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any, Dict, List, Sequence
import sqlalchemy as sa
from sqlalchemy.engine import Engine
from .extractor.settings import DbSettings
class SqlValidationError(RuntimeError):
"""Raised when a generated SQL statement fails safety checks."""
PROHIBITED_KEYWORDS: Sequence[str] = (
"INSERT",
"UPDATE",
"DELETE",
"MERGE",
"DROP",
"ALTER",
"TRUNCATE",
"CREATE",
"EXEC",
"EXECUTE",
"GRANT",
"REVOKE",
"BEGIN",
"COMMIT",
"ROLLBACK",
)
UNSUPPORTED_PATTERNS: Sequence[str] = (
r"\bILIKE\b",
r"NULLS\s+LAST",
r"NULLS\s+FIRST",
r"\bLIMIT\b",
r"\bOFFSET\b",
r"\bUSING\b",
)
@dataclass
class SqlExecutionResult:
sql: str
rows: List[Dict[str, Any]]
columns: List[str]
def _build_engine(settings: DbSettings) -> Engine:
connection_string = settings.connection_string()
uri = "mssql+pyodbc:///?odbc_connect=" + sa.engine.url.quote_plus(connection_string)
return sa.create_engine(uri, fast_executemany=True)
def _clean_sql(sql: str) -> str:
return sql.strip().rstrip(";")
def _contains_multiple_statements(sql: str) -> bool:
body = sql.rstrip()
if ";" not in body:
return False
# Allow a single trailing semicolon but forbid anything after it
last_semicolon = body.rfind(";")
trailing = body[last_semicolon + 1 :].strip()
return trailing != ""
def _enforce_top_clause(sql: str, max_rows: int) -> str:
pattern = re.compile(r"select\s+(distinct\s+)?", re.IGNORECASE)
leading_whitespace = len(sql) - len(sql.lstrip())
body = sql.lstrip()
match = pattern.match(body)
if not match:
return sql
# Detect existing TOP clause in the initial projection
leading_segment = body[: match.end() + 20].lower()
if "top" in leading_segment:
return sql
prefix = match.group(0)
remainder = body[match.end() :]
if match.group(1):
# prefix already includes "SELECT DISTINCT "
replacement = prefix + f"TOP ({max_rows}) " + remainder
else:
replacement = "SELECT TOP ({}) ".format(max_rows) + body[len("SELECT ") :]
return sql[:leading_whitespace] + replacement
def sanitize_sql(sql: str, max_rows: int = 500) -> str:
"""Ensure the SQL is safe to execute and apply a row limit."""
candidate = _clean_sql(sql)
if not candidate:
raise SqlValidationError("Generated SQL is empty.")
lowered = candidate.lstrip().lower()
if not lowered.startswith("select"):
raise SqlValidationError("Only SELECT statements are allowed.")
if _contains_multiple_statements(candidate):
raise SqlValidationError("Multiple statements detected; reject for safety.")
upper = candidate.upper()
for keyword in PROHIBITED_KEYWORDS:
if re.search(rf"\b{keyword}\b", upper):
raise SqlValidationError(f"Statement contains disallowed keyword: {keyword}")
for pattern in UNSUPPORTED_PATTERNS:
if re.search(pattern, candidate, flags=re.IGNORECASE):
raise SqlValidationError("Statement contains non-SQL Server syntax (e.g., ILIKE, NULLS LAST, LIMIT, OFFSET, USING).")
if max_rows <= 0:
raise SqlValidationError("max_rows must be greater than zero.")
limited = _enforce_top_clause(candidate, max_rows=max_rows)
return limited
def execute_sql(sql: str, max_rows: int = 500) -> SqlExecutionResult:
"""Validate and run the provided SQL against the configured MSSQL database."""
sanitized = sanitize_sql(sql, max_rows=max_rows)
settings = DbSettings.from_env()
engine = _build_engine(settings)
with engine.connect() as conn:
result = conn.execute(sa.text(sanitized))
columns = list(result.keys())
rows = [dict(row._mapping) for row in result]
return SqlExecutionResult(sql=sanitized, rows=rows, columns=columns)

View File

@@ -0,0 +1,41 @@
# SQL Agent Web UI
A lightweight FastAPI + vanilla JS frontend for interacting with the SugarScale SQL agent.
## Backend
Located at `db_agent/ui/backend/main.py`. It exposes:
- `POST /api/query` wraps the existing agent pipeline (LLM + optional SQL execution + logging).
- `GET /health` health probe.
- Serves the static frontend and index page.
### Run locally
```powershell
# Activate your virtual environment first
uvicorn db_agent.ui.backend.main:app --reload --host 0.0.0.0 --port 8000
```
The UI will be available at `http://localhost:8000/`. Adjust the host/port as needed.
## Frontend
Files under `db_agent/ui/frontend/`:
- `index.html` main page with the question form, quick-reference card, and results display.
- `static/app.js` handles form submission, fetches `/api/query`, renders results, and powers CSV/HTML exports plus reset logic.
- `static/styles.css` modern styling.
## Configuration Notes
- The backend reuses environment variables (`DB_SERVER`, `DB_DATABASE`, etc.) for SQL execution, so ensure they are set before starting the FastAPI server. Dot-source `db_agent/scripts/Set-DbEnv.ps1` to populate them in one step and supply `-Password (Read-Host -AsSecureString)` if you prefer an inline prompt.
- The backend expects the LLM endpoint configured in `db_agent/client.LlmConfig.base_url` (defaults to `http://192.168.0.30:8080`). Update if your TGI server runs elsewhere.
- Interaction logs still append to `db_agent/logs/query_log.jsonl` by default.
- Set `UI_BASIC_USER` and `UI_BASIC_PASSWORD` to enable HTTP Basic auth for the web UI/API. When present, every route except `/health` requires those credentials; omit both variables to leave the UI open (useful for local dev).
## UI Tips
- The form defaults to executing SQL and pre-populates table hints with `dbo.SugarLoadData`; use the Reset button to restore these defaults while clearing previous results.
- After running a query, download the result grid as CSV via **Export CSV** or grab a formatted HTML report with **Download Report** for sharing.
- The quick-reference panel beside the form lists common companies/destinations—update it as real-world values change so operators have fresh context.
## Next Ideas
- Add user authentication or API keys.
- Save favorite queries or table presets.
- Stream results for large datasets.

View File

@@ -0,0 +1,239 @@
from __future__ import annotations
import logging
import json
import base64
import os
import secrets
from pathlib import Path
from typing import Iterable, Literal, Optional
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from starlette.middleware.base import BaseHTTPMiddleware
from pydantic import BaseModel, Field
from db_agent.client import SqlAgentClient, default_client
from db_agent.log_utils import log_interaction
from db_agent.sql_executor import SqlExecutionResult, SqlValidationError, execute_sql
logger = logging.getLogger("db_agent_ui")
class BasicAuthMiddleware(BaseHTTPMiddleware):
"""Protect routes with HTTP Basic auth when credentials are configured."""
def __init__(
self,
app: FastAPI,
*,
username: str,
password: str,
exclude_prefixes: Iterable[str] = (),
) -> None:
super().__init__(app)
self.username = username
self.password = password
self.exclude_prefixes = tuple(exclude_prefixes)
async def dispatch(self, request: Request, call_next): # type: ignore[override]
if self.exclude_prefixes and request.url.path.startswith(self.exclude_prefixes):
return await call_next(request)
header = request.headers.get("Authorization")
if not header or not header.startswith("Basic "):
return self._unauthorized()
try:
decoded = base64.b64decode(header[6:]).decode("utf-8")
except (ValueError, UnicodeDecodeError):
return self._unauthorized()
provided_user, _, provided_password = decoded.partition(":")
if not (secrets.compare_digest(provided_user, self.username) and secrets.compare_digest(provided_password, self.password)):
return self._unauthorized()
return await call_next(request)
@staticmethod
def _unauthorized() -> Response:
return Response(status_code=401, headers={"WWW-Authenticate": "Basic realm=\"SQL Agent UI\""})
class QueryRequest(BaseModel):
question: str = Field(..., description="Natural language question")
tables: Optional[list[str]] = Field(default=None, description="Optional table hints")
execute: bool = Field(default=False, description="Run the generated SQL against MSSQL")
max_rows: int = Field(default=500, ge=1, description="Row cap applied via TOP clause")
feedback: Optional[str] = Field(default=None, description="Optional user feedback tag")
class QueryResponse(BaseModel):
sql: str
summary: str
sanitized_sql: Optional[str] = None
rows: Optional[list[dict[str, object]]] = None
columns: Optional[list[str]] = None
row_count: Optional[int] = None
llm_warning: Optional[str] = None
execution_status: Optional[str] = None
execution_error: Optional[str] = None
user_feedback: Optional[str] = None
app = FastAPI(title="SugarScale SQL Agent UI", version="0.1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
basic_user = os.getenv("UI_BASIC_USER")
basic_password = os.getenv("UI_BASIC_PASSWORD")
if basic_user and basic_password:
logger.info("Enabling HTTP Basic auth for UI endpoints")
app.add_middleware(
BasicAuthMiddleware,
username=basic_user,
password=basic_password,
exclude_prefixes=("/health",),
)
elif basic_user or basic_password:
logger.warning("UI basic auth is partially configured; set both UI_BASIC_USER and UI_BASIC_PASSWORD to enable it.")
frontend_dir = Path(__file__).resolve().parent.parent / "frontend"
static_dir = frontend_dir / "static"
if static_dir.exists():
app.mount("/static", StaticFiles(directory=static_dir), name="static")
_agent_client: Optional[SqlAgentClient] = None
def get_client() -> SqlAgentClient:
global _agent_client
if _agent_client is None:
_agent_client = default_client()
return _agent_client
class FeedbackRequest(BaseModel):
question: str = Field(..., description="Question that produced the answer")
sql: str = Field(..., description="Generated SQL that was reviewed")
summary: Optional[str] = None
sanitized_sql: Optional[str] = None
feedback: Literal["correct", "incorrect"] = Field(..., description="User feedback tag")
@app.post("/api/query", response_model=QueryResponse)
def query_endpoint(payload: QueryRequest) -> QueryResponse:
client = get_client()
response = client.query(question=payload.question, table_hints=payload.tables)
sql = response.get("sql", "").strip()
summary = response.get("summary", "").strip()
warning = response.get("llm_warning")
raw_response = json.dumps(response, ensure_ascii=False)
sanitized_sql = None
rows = None
columns = None
row_count = None
execution_status = None
execution_error = None
normalized_sql = sql.lstrip()
has_sql = bool(normalized_sql)
sql_is_select = normalized_sql.lower().startswith("select") if has_sql else False
if payload.execute:
if not has_sql:
warning = warning or "Model did not return executable SQL; nothing was run."
elif not sql_is_select:
warning = warning or "Model did not return a valid SELECT statement; execution skipped."
else:
try:
exec_result: SqlExecutionResult = execute_sql(
normalized_sql,
max_rows=payload.max_rows,
)
except SqlValidationError as exc:
execution_error = str(exc)
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc: # pylint: disable=broad-except
logger.exception("SQL execution error")
execution_error = str(exc)
raise HTTPException(status_code=500, detail="SQL execution failed") from exc
else:
sanitized_sql = exec_result.sql
rows = exec_result.rows
columns = exec_result.columns
row_count = len(rows)
execution_status = "success"
log_interaction(
question=payload.question,
generated_sql=sql,
summary=summary,
sanitized_sql=sanitized_sql,
row_count=row_count,
execution_status=execution_status,
execution_error=execution_error,
raw_response=raw_response,
user_feedback=payload.feedback,
metadata={
"source": "ui",
"execute": payload.execute,
"tables": payload.tables,
"llm_warning": warning,
},
)
return QueryResponse(
sql=sql,
summary=summary,
sanitized_sql=sanitized_sql,
rows=rows,
columns=columns,
row_count=row_count,
llm_warning=warning,
execution_status=execution_status,
execution_error=execution_error,
user_feedback=payload.feedback,
)
@app.post("/api/feedback")
def record_feedback(payload: FeedbackRequest) -> dict[str, str]:
feedback_value = payload.feedback.lower()
log_interaction(
question=payload.question,
generated_sql=payload.sql,
summary=payload.summary or "",
sanitized_sql=payload.sanitized_sql,
row_count=None,
execution_status=None,
execution_error=None,
raw_response=None,
user_feedback=feedback_value,
metadata={
"source": "ui-feedback",
"feedback_only": True,
},
)
return {"status": "recorded"}
@app.get("/health")
def healthcheck() -> dict[str, str]:
return {"status": "ok"}
@app.get("/")
def index() -> FileResponse:
return FileResponse(frontend_dir / "index.html")

View File

@@ -0,0 +1,123 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>SugarScale SQL Agent</title>
<link rel="stylesheet" href="/static/styles.css" />
</head>
<body>
<header>
<h1>SugarScale SQL Agent</h1>
<p>Ask natural-language questions and execute the generated SQL.</p>
</header>
<main>
<div class="form-columns">
<section class="panel form-panel">
<form id="query-form">
<label for="question">Question</label>
<textarea id="question" name="question" rows="3" placeholder="e.g., How many loads were completed yesterday?" required></textarea>
<label for="tables">Table hints (comma-separated)</label>
<input id="tables" name="tables" type="text" placeholder="dbo.SugarLoadData" value="dbo.SugarLoadData" />
<div class="options">
<label>
<input type="checkbox" id="execute" name="execute" checked /> Execute SQL
</label>
<label for="max-rows">Max rows</label>
<input id="max-rows" name="max_rows" type="number" min="1" value="500" />
</div>
<div class="actions">
<button type="submit">Run</button>
<button type="button" id="reset-form" class="secondary">Reset</button>
</div>
</form>
</section>
<section class="panel helper-panel">
<label>Quick Reference</label>
<p class="helper-intro">Use these static values to include detailed data in your questions.</p>
<div class="helper-grid">
<div>
<label>Companies</label>
<ul>
<li>BigDawg</li>
<li>CSC</li>
<li>LACA</li>
<li>LASUCA</li>
<li>Ralph Callier</li>
</ul>
</div>
<div>
<label>Destinations</label>
<ul>
<li>LSR</li>
<li>CSC</li>
<li>Barge</li>
<li>Other</li>
</ul>
</div>
</div>
<p class="helper-intro">Dates can be represented as 10-12-25, 10/12/25, ect. Time can be exact or as simple as 6am, 4pm, ect.</p>
<div>
<label>Sample Questions</label>
<ul>
<li>List all loads from yesterday.</li>
<li>Show all loads hauled by LACA last week.</li>
<li>Show all loads hauled to barge this week.</li>
<li>Total tons hauled on 10/14/25.</li>
</ul>
</div>
</section>
</div>
<section class="panel results-panel" id="results" hidden>
<h2>Results</h2>
<div class="warning" id="warning" hidden></div>
<div id="summary"></div>
<details>
<summary>Generated SQL</summary>
<pre><code id="generated-sql"></code></pre>
</details>
<details id="sanitized-block" hidden>
<summary>Clean SQL (executed)</summary>
<pre><code id="sanitized-sql"></code></pre>
</details>
<div id="row-count"></div>
<div class="table-wrapper" id="table-wrapper" hidden>
<table id="result-table">
<thead id="result-thead"></thead>
<tbody id="result-tbody"></tbody>
</table>
</div>
<div class="export" id="export-wrapper" hidden>
<button type="button" id="export-results" class="secondary">Export CSV</button>
<button type="button" id="export-report" class="secondary">Download Report</button>
</div>
<div id="feedback-panel" hidden>
<h3>Was this answer helpful?</h3>
<div class="feedback-actions">
<button type="button" id="feedback-correct">Mark Correct</button>
<button type="button" id="feedback-incorrect" class="secondary">Needs Work</button>
</div>
<p id="feedback-status" hidden></p>
</div>
</section>
<section class="panel error" id="error" hidden>
<h2>Error</h2>
<pre id="error-message"></pre>
</section>
</main>
<footer>
<small>Powered by the SugarScale SQL agent.</small>
</footer>
<script src="/static/app.js" type="module"></script>
</body>
</html>

View File

@@ -0,0 +1,365 @@
const form = document.getElementById("query-form");
const resultsPanel = document.getElementById("results");
const errorPanel = document.getElementById("error");
const warningEl = document.getElementById("warning");
const summaryEl = document.getElementById("summary");
const generatedSqlEl = document.getElementById("generated-sql");
const sanitizedBlock = document.getElementById("sanitized-block");
const sanitizedSqlEl = document.getElementById("sanitized-sql");
const rowCountEl = document.getElementById("row-count");
const tableWrapper = document.getElementById("table-wrapper");
const tableEl = document.getElementById("result-table");
const tableHeadEl = document.getElementById("result-thead");
const tableBodyEl = document.getElementById("result-tbody");
const errorMessageEl = document.getElementById("error-message");
const feedbackPanel = document.getElementById("feedback-panel");
const feedbackCorrectBtn = document.getElementById("feedback-correct");
const feedbackIncorrectBtn = document.getElementById("feedback-incorrect");
const feedbackStatus = document.getElementById("feedback-status");
const resetBtn = document.getElementById("reset-form");
const exportWrapper = document.getElementById("export-wrapper");
const exportBtn = document.getElementById("export-results");
const reportBtn = document.getElementById("export-report");
let latestResult = null;
function resetPanels() {
resultsPanel.hidden = true;
errorPanel.hidden = true;
warningEl.hidden = true;
warningEl.textContent = "";
summaryEl.textContent = "";
generatedSqlEl.textContent = "";
sanitizedBlock.hidden = true;
sanitizedSqlEl.textContent = "";
rowCountEl.textContent = "";
tableEl.hidden = true;
tableWrapper.hidden = true;
tableHeadEl.innerHTML = "";
tableBodyEl.innerHTML = "";
errorMessageEl.textContent = "";
feedbackPanel.hidden = true;
feedbackStatus.hidden = true;
feedbackStatus.textContent = "";
exportWrapper.hidden = true;
exportBtn.disabled = true;
if (reportBtn) {
reportBtn.disabled = true;
}
latestResult = null;
}
function renderTable(columns, rows) {
if (!columns || !rows || rows.length === 0) {
tableEl.hidden = true;
tableWrapper.hidden = true;
return false;
}
tableHeadEl.innerHTML = "";
tableBodyEl.innerHTML = "";
const headerRow = document.createElement("tr");
columns.forEach((col) => {
const th = document.createElement("th");
th.textContent = col;
headerRow.appendChild(th);
});
tableHeadEl.appendChild(headerRow);
rows.forEach((row) => {
const tr = document.createElement("tr");
columns.forEach((col) => {
const td = document.createElement("td");
const value = row[col];
td.textContent = value === null || value === undefined ? "" : String(value);
tr.appendChild(td);
});
tableBodyEl.appendChild(tr);
});
tableEl.hidden = false;
tableWrapper.hidden = false;
return true;
}
function toCsv(columns, rows) {
const escapeCell = (value) => {
if (value === null || value === undefined) {
return "";
}
const stringValue = String(value);
if (/[",\n]/.test(stringValue)) {
return `"${stringValue.replace(/"/g, '""')}"`;
}
return stringValue;
};
const header = columns.map(escapeCell).join(",");
const lines = rows.map((row) => columns.map((col) => escapeCell(row[col])).join(","));
return [header, ...lines].join("\n");
}
function downloadCsv(filename, columns, rows) {
const csvContent = toCsv(columns, rows);
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
form.addEventListener("submit", async (event) => {
event.preventDefault();
resetPanels();
const question = document.getElementById("question").value.trim();
const tablesValue = document.getElementById("tables").value.trim();
const execute = document.getElementById("execute").checked;
const maxRows = parseInt(document.getElementById("max-rows").value, 10) || 500;
if (!question) {
errorPanel.hidden = false;
errorMessageEl.textContent = "Please enter a question.";
return;
}
const payload = {
question,
tables: tablesValue ? tablesValue.split(",").map((s) => s.trim()).filter(Boolean) : undefined,
execute,
max_rows: maxRows,
feedback: null,
};
try {
const response = await fetch("/api/query", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || `Request failed with status ${response.status}`);
}
const data = await response.json();
summaryEl.textContent = data.summary || "(No summary provided)";
generatedSqlEl.textContent = data.sql || "";
if (data.llm_warning) {
warningEl.textContent = data.llm_warning;
warningEl.hidden = false;
}
if (data.sanitized_sql) {
sanitizedSqlEl.textContent = data.sanitized_sql;
sanitizedBlock.hidden = false;
}
if (typeof data.row_count === "number") {
rowCountEl.textContent = `Rows returned: ${data.row_count}`;
}
const hasRows = renderTable(data.columns, data.rows);
latestResult = {
question,
sql: data.sql || "",
summary: data.summary || "",
sanitized_sql: data.sanitized_sql || null,
columns: Array.isArray(data.columns) ? data.columns : [],
rows: Array.isArray(data.rows) ? data.rows : [],
warning: data.llm_warning || null,
rowCount: typeof data.row_count === "number" ? data.row_count : null,
};
feedbackPanel.hidden = false;
feedbackStatus.hidden = true;
feedbackStatus.textContent = "";
const canExportTable = hasRows && latestResult.rows.length > 0;
if (reportBtn) {
exportWrapper.hidden = false;
reportBtn.disabled = false;
exportBtn.disabled = !canExportTable;
} else if (canExportTable) {
exportWrapper.hidden = false;
exportBtn.disabled = false;
}
resultsPanel.hidden = false;
} catch (error) {
errorPanel.hidden = false;
errorMessageEl.textContent = error.message || String(error);
}
});
resetBtn.addEventListener("click", () => {
form.reset();
document.getElementById("tables").value = document.getElementById("tables").defaultValue;
document.getElementById("max-rows").value = document.getElementById("max-rows").defaultValue;
document.getElementById("execute").checked = document.getElementById("execute").defaultChecked;
resetPanels();
});
exportBtn.addEventListener("click", () => {
if (!latestResult || !latestResult.columns || latestResult.rows.length === 0) {
return;
}
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const filename = `sql-agent-results-${timestamp}.csv`;
downloadCsv(filename, latestResult.columns, latestResult.rows);
});
function escapeHtml(value) {
if (value === null || value === undefined) {
return "";
}
return String(value)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#39;");
}
function buildReportHtml(result) {
const timestamp = new Date().toLocaleString();
const rowsHtml = result.rows
.map(
(row) =>
`<tr>${result.columns
.map((col) => `<td>${escapeHtml(row[col])}</td>`)
.join("")}</tr>`
)
.join("");
const tableSection =
result.columns.length && result.rows.length
? `<table><thead><tr>${result.columns
.map((col) => `<th>${escapeHtml(col)}</th>`)
.join("")}</tr></thead><tbody>${rowsHtml}</tbody></table>`
: `<p>No row data was returned.</p>`;
const sanitizedSection = result.sanitized_sql
? `<h3>Sanitized SQL</h3><pre>${escapeHtml(result.sanitized_sql)}</pre>`
: "";
const warningSection = result.warning
? `<div class="warning">${escapeHtml(result.warning)}</div>`
: "";
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>SQL Agent Report</title>
<style>
body { font-family: 'Segoe UI', sans-serif; margin: 2rem auto; max-width: 960px; color: #0f172a; }
h1, h2, h3 { color: #1e3a8a; }
.meta { margin-bottom: 1.5rem; }
.meta dt { font-weight: 600; }
.meta dd { margin: 0 0 0.75rem 0; }
pre { background: #0f172a; color: #f8fafc; padding: 1rem; border-radius: 8px; overflow-x: auto; }
table { width: 100%; border-collapse: collapse; margin-top: 1.5rem; }
th, td { border: 1px solid #e2e8f0; padding: 0.75rem; text-align: left; }
th { background: #e2e8f0; }
.warning { background: #fef3c7; border-left: 4px solid #f59e0b; padding: 0.75rem 1rem; border-radius: 8px; margin-bottom: 1.5rem; }
footer { margin-top: 2rem; font-size: 0.85rem; color: #475569; }
</style>
</head>
<body>
<h1>SQL Agent Report</h1>
<dl class="meta">
<dt>Generated</dt>
<dd>${escapeHtml(timestamp)}</dd>
<dt>Question</dt>
<dd>${escapeHtml(result.question)}</dd>
<dt>Summary</dt>
<dd>${escapeHtml(result.summary || '(No summary provided)')}</dd>
<dt>Rows Returned</dt>
<dd>${result.rowCount !== null ? escapeHtml(result.rowCount) : 'n/a'}</dd>
</dl>
${warningSection}
<h2>Generated SQL</h2>
<pre>${escapeHtml(result.sql)}</pre>
${sanitizedSection}
<h2>Result Preview</h2>
${tableSection}
<footer>Report generated by the SugarScale SQL Agent UI.</footer>
</body>
</html>`;
}
function downloadReport(filename, html) {
const blob = new Blob([html], { type: "text/html;charset=utf-8;" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
if (reportBtn) {
reportBtn.addEventListener("click", () => {
if (!latestResult) {
return;
}
const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
const filename = `sql-agent-report-${timestamp}.html`;
const html = buildReportHtml(latestResult);
downloadReport(filename, html);
});
}
async function sendFeedback(tag) {
if (!latestResult) {
return;
}
const payload = {
question: latestResult.question,
sql: latestResult.sql,
summary: latestResult.summary,
sanitized_sql: latestResult.sanitized_sql,
feedback: tag,
};
feedbackStatus.hidden = false;
feedbackStatus.textContent = "Sending feedback...";
feedbackCorrectBtn.disabled = true;
feedbackIncorrectBtn.disabled = true;
try {
const response = await fetch("/api/feedback", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || `Feedback request failed with status ${response.status}`);
}
feedbackStatus.textContent = tag === "correct" ? "Marked as correct." : "Marked as needs work.";
} catch (error) {
feedbackStatus.textContent = error.message || String(error);
} finally {
feedbackCorrectBtn.disabled = false;
feedbackIncorrectBtn.disabled = false;
}
}
feedbackCorrectBtn.addEventListener("click", () => sendFeedback("correct"));
feedbackIncorrectBtn.addEventListener("click", () => sendFeedback("incorrect"));

Some files were not shown because too many files have changed in this diff Show More