Aniruddha7 commited on
Commit
6c4e218
·
1 Parent(s): 804d00a

Deploy QueryLens V2 (code only)

Browse files
.dockerignore ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Exclude heavy folders from Docker image
2
+ **/__pycache__
3
+ **/.venv
4
+ **/.git
5
+ **/.ipynb_checkpoints
6
+ **/hf_cache
7
+ **/node_modules
8
+
9
+ # Exclude local database data
10
+ **/postgres-data
11
+ **/mysql-data
12
+
13
+ # Exclude large model weights and research artifacts
14
+ Agent/Gemma3_1B_weights
15
+ Agent/merged_gemma1b_text2Sql
16
+ Agent/merged_gemma3_1b_text2Sql
17
+ Agent/Qwen2.5_3b_weights
18
+ Agent/Qwen2.5-3B-Instruct
19
+ merged_qwen2_5_3b_text2sql
20
+ merged_gemma3_1b_text2sql
21
+ .venv-merge/
22
+
23
+ # Exclude all Jupyter Notebooks EXCEPT the proof-of-work notebook
24
+ **/*.ipynb
25
+ !Fine_Tuning_Qwen_2_5_3B.ipynb
26
+ **/.ipynb_checkpoints
27
+
28
+ # Exclude redundant project clutter
29
+ backups/
30
+ debug_files/
31
+ test_files/
32
+ test_results/
33
+ dump-mysql.bat
34
+ dump-postgres.bat
35
+ agentic_improvements.md
36
+ invariants_analysis.md
37
+ progress_summary.txt
38
+ mcp_server.log
39
+ merge.log
40
+ response.json
41
+ run-dev.ps1
42
+ setup_ollama.bat
43
+
44
+
45
+ # Exclude experimental/redundant Python scripts
46
+ Agent/trial*.py
47
+ Agent/test*.py
48
+ Agent/old_*.py
49
+ Agent/OLLAMA_GPU_NOTES.md
50
+ **/debug_*.py
51
+
52
+ # Exclude local uploads and generated files (keep empty folder)
53
+ chat_store/*
54
+ !chat_store/.gitkeep
55
+ !uploads/.gitkeep
56
+
57
+ # Exclude local configuration (Hugging Face uses Secrets instead)
58
+ .env
59
+ .env.local
60
+
61
+ # Exclude local logs and IDE settings
62
+ *.log
63
+ .vscode/
64
+ .idea/
65
+ .DS_Store
66
+
67
+ # Exclude Python build artifacts
68
+ __pycache__/
69
+ *.pyc
70
+ *.pyo
71
+ *.pyd
72
+ .Python
73
+ env/
74
+ venv/
75
+ .venv/
76
+ pip-log.txt
77
+ pip-delete-this-directory.txt
78
+ .toast
79
+ .mypy_cache/
80
+ .pytest_cache/
81
+ .hypothesis/
82
+
83
+ # Exclude large local data
84
+ uploads/*
85
+ !uploads/.gitkeep
86
+ chat_store/*
87
+ !chat_store/docs/.gitkeep
88
+ !chat_store/.gitkeep
89
+ .idea/
.env.example ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core DB
2
+ # DB_CONNECTION_URL=postgresql://user:pass@localhost:5432/dbname
3
+
4
+ # ── Text-to-SQL LLM ──────────────────────────────────────────────
5
+ # Recommended: HF Inference API (same as the Hugging Face Spaces deployment).
6
+ # Set USE_HF_CLOUD=1 to force cloud-only. With USE_HF_CLOUD=0 the local Ollama
7
+ # model is still preferred, but if it is not installed and HF_API_TOKEN is set,
8
+ # the worker auto-falls back to HF Inference automatically.
9
+ USE_HF_CLOUD=1
10
+ HF_API_TOKEN=
11
+ HF_LLM_MODEL=Qwen/Qwen2.5-Coder-7B-Instruct
12
+
13
+ # Cloud VQA via Groq (free tier)
14
+ GROQ_API_KEY=
15
+ GROQ_VISION_MODEL=qwen/qwen3.8-27b
16
+
17
+ # Local Ollama (optional — only when models are installed locally)
18
+ # USE_HF_CLOUD=0
19
+ # OLLAMA_BASE_URL=http://localhost:11434
20
+ # OLLAMA_MODEL_NAME=qwen2.5-coder:1.5b
21
+ # GRANITE_MODEL_PATH=qwen3.5:2b
22
+ # OLLAMA_OCR_QA_MODEL=gemma3:1b-it-qat
23
+ # GRANITE_MODEL=qwen3.5:2b
24
+
25
+ # Workers/timeouts
26
+ WORKER_PORT=8700
27
+ MCP_PORT=8701
28
+ OCR_QA_TIMEOUT=45
29
+ INVARIANTS_BASE_TIMEOUT=180
.gitignore ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Local Models and Weights
2
+ Agent/*_weights/
3
+ Agent/Qwen*/
4
+ Agent/Gemma*/
5
+ Agent/merged_*/
6
+ merged_*/
7
+ *.bin
8
+ *.gguf
9
+ *.onnx
10
+
11
+ # Large Sample Database (Not needed in cloud) — EXCEPT the tiny bundled
12
+ # demo SQLite file, which serves as the built-in demo_employee profile on
13
+ # Hugging Face Spaces (no external DB service runs there).
14
+ employee-sample-database/*
15
+ !employee-sample-database/sqlite/
16
+ employee-sample-database/sqlite/*
17
+ !employee-sample-database/sqlite/dataset_small/
18
+ employee-sample-database/sqlite/dataset_small/*
19
+ !employee-sample-database/sqlite/dataset_small/employee.db
20
+
21
+ # Data and History
22
+ chat_store/
23
+ Agent/chat_store_private.json
24
+
25
+ # Docker and DB
26
+ docker/data/
27
+
28
+ # Python
29
+ __pycache__/
30
+ *.py[cod]
31
+ *.egg-info/
32
+ *.egg
33
+ *.pyo
34
+ *.pyd
35
+ *.so
36
+
37
+ # Virtual environments
38
+ venv/
39
+ .venv/
40
+ .env
41
+ .env.local
42
+ !.env.example
43
+
44
+ # Jupyter Notebooks and checkpoints
45
+ *.ipynb
46
+ .ipynb_checkpoints/
47
+
48
+ # Experimental/Redundant Scripts
49
+ Agent/trial*.py
50
+ Agent/old_*.py
51
+ Agent/requirements-merge.txt
52
+ debug_files/
53
+ test_results/
54
+
55
+ # Data and Uploads (Keep the folders, ignore the contents)
56
+ uploads/*
57
+ !uploads/.gitkeep
58
+ chat_store/docs/*
59
+ !chat_store/docs/.gitkeep
60
+
61
+ # OS-specific and IDEs
62
+ .DS_Store
63
+ Thumbs.db
64
+ .vscode/
65
+ .idea/
66
+
67
+ # Logs
68
+ *.log
69
+ mcp_server.log
70
+ merge.log
71
+ response.json
Agent/agentic_workflow.py ADDED
The diff for this file is too large to render. See raw diff
 
Agent/chart_contract.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Chart contract — turns query result rows into a rendering-agnostic chart spec.
3
+
4
+ The text2SQL pipeline produces plain result rows. This module detects rows that
5
+ visualize well (category breakdowns, time series, comparisons) and produces a
6
+ compact JSON spec embedded in the answer text as:
7
+
8
+ <<<CHART_JSON>>>{...spec...}<<<END_CHART_JSON>>>
9
+
10
+ The worker strips the marker out of the user-visible answer and ships the spec
11
+ separately. The web UI renders it with ECharts in the sepia palette. If no
12
+ reliable vega-like shape is found, no marker is added and the UI falls back to
13
+ tables/text — chart detection must never corrupt a correct answer.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import re
19
+ from datetime import date, datetime
20
+ from decimal import Decimal
21
+ from typing import Any, Dict, List, Optional, Tuple
22
+
23
+ CHART_OPEN = "<<<CHART_JSON>>>"
24
+ CHART_CLOSE = "<<<END_CHART_JSON>>>"
25
+
26
+ MAX_CHART_ROWS = 60 # cap categories drawn
27
+ MAX_LABEL_LEN = 40 # truncate long labels
28
+ PIE_MAX_ROWS = 8 # pies stay readable up to ~8 slices
29
+
30
+ SERIES_NAME_HINTS = (
31
+ ("count", "count"), ("total", "total"), ("sum", "total"),
32
+ ("avg", "average"), ("average", "average"), ("min", "minimum"),
33
+ ("max", "maximum"), ("salary", "value"), ("amount", "value"),
34
+ )
35
+
36
+ DATE_RE = re.compile(
37
+ r"^\d{4}([-/.]\d{1,2}([-/.]\d{1,2})?)?$" # 2024 / 2024-01 / 2024-01-01
38
+ )
39
+
40
+
41
+ # ---------------------------------------------------------------------------
42
+ # Helpers
43
+ # ---------------------------------------------------------------------------
44
+ def _num(v: Any) -> Optional[float]:
45
+ if isinstance(v, bool):
46
+ return None
47
+ if isinstance(v, (int, float)) and v == v: # NaN guard
48
+ return float(v)
49
+ if isinstance(v, Decimal):
50
+ try:
51
+ return float(v)
52
+ except Exception:
53
+ return None
54
+ if isinstance(v, str):
55
+ s = v.strip().replace(",", "")
56
+ if re.fullmatch(r"-?\d+(\.\d+)?", s):
57
+ try:
58
+ return float(s)
59
+ except ValueError:
60
+ return None
61
+ return None
62
+
63
+
64
+ def _label(v: Any) -> str:
65
+ if v is None:
66
+ return "(none)"
67
+ if isinstance(v, (date, datetime)):
68
+ return str(v)[:MAX_LABEL_LEN]
69
+ s = str(v).strip()
70
+ if len(s) > MAX_LABEL_LEN:
71
+ s = s[: MAX_LABEL_LEN - 1] + "…"
72
+ return s
73
+
74
+
75
+ def _is_dateish(v: Any) -> bool:
76
+ if isinstance(v, (date, datetime)):
77
+ return True
78
+ s = str(v).strip()
79
+ return bool(s) and bool(DATE_RE.match(s))
80
+
81
+
82
+ def _nice_series_name(col: str) -> str:
83
+ c = (col or "").strip()
84
+ cl = c.lower()
85
+ for key, nice in SERIES_NAME_HINTS:
86
+ if key in cl:
87
+ base = c.split("(")[0].strip() # strip "AVG(" noise in aliases
88
+ return base or nice
89
+ return c
90
+
91
+
92
+ # ---------------------------------------------------------------------------
93
+ # Detection
94
+ # ---------------------------------------------------------------------------
95
+ def detect_chart_spec(results: List[Dict[str, Any]], question: str = "") -> Optional[Dict[str, Any]]:
96
+ """Return a chart spec dict when `results` visualize well, else None.
97
+
98
+ Spec shape (ECharts-friendly, library-agnostic):
99
+ {
100
+ "type": "pie" | "bar" | "line",
101
+ "title": str, # derived from the question
102
+ "xlabel": str, "ylabel": str,
103
+ "x": [labels], # categories or time points
104
+ "series": [{"name": str, "values": [numbers]}],
105
+ "rows_in_result": int
106
+ }
107
+ """
108
+ if not results or not isinstance(results, list):
109
+ return None
110
+ if not isinstance(results[0], dict) or results[0].get("error"):
111
+ return None
112
+
113
+ rows = [r for r in results if isinstance(r, dict)]
114
+ if len(rows) > MAX_CHART_ROWS:
115
+ return None
116
+
117
+ cols = list(rows[0].keys())
118
+ if not cols:
119
+ return None
120
+
121
+ label_col: Optional[str] = None
122
+ time_col: Optional[str] = None
123
+ numeric_cols: List[str] = []
124
+
125
+ for c in cols:
126
+ vals = [r.get(c) for r in rows]
127
+ non_none = [v for v in vals if v is not None]
128
+ if not non_none:
129
+ continue
130
+ # Date-like strings take precedence over numeric-string coercion
131
+ # (a "2020"/"2024-01" column is a time axis, not a measurement).
132
+ all_dateish = all(_is_dateish(v) for v in non_none)
133
+ if all_dateish and time_col is None and label_col is None:
134
+ time_col = c
135
+ continue
136
+ nums = [_num(v) for v in vals]
137
+ n_numeric = sum(1 for n in nums if n is not None)
138
+ if n_numeric == len(non_none):
139
+ numeric_cols.append(c)
140
+ elif label_col is None:
141
+ uniq = {str(v) for v in non_none}
142
+ if 0 < len(uniq) <= MAX_CHART_ROWS: # degenerate constant columns still ok
143
+ label_col = c
144
+
145
+ if time_col:
146
+ label_col = time_col
147
+
148
+ if label_col is None or not numeric_cols:
149
+ return None
150
+
151
+ labels = [_label(r.get(label_col)) for r in rows]
152
+
153
+ series: List[Dict[str, Any]] = []
154
+ for c in numeric_cols[:3]: # at most 3 series keeps charts readable
155
+ values: List[Optional[float]] = []
156
+ ok = True
157
+ for r in rows:
158
+ n = _num(r.get(c))
159
+ if n is None:
160
+ ok = False
161
+ break
162
+ values.append(n)
163
+ if ok and any(v != 0 for v in values):
164
+ values = [round(v, 6) for v in values]
165
+ series.append({"name": _nice_series_name(c), "values": values})
166
+
167
+ if not series:
168
+ return None
169
+
170
+ # Chart type selection --------------------------------------------------
171
+ ql = (question or "").lower()
172
+ proportion_intent = any(
173
+ k in ql for k in ("distribution", "share", "percentage", "percent", "proportion", "%", "breakdown", "split")
174
+ )
175
+ trend_intent = time_col is not None or any(
176
+ k in ql for k in ("trend", "over time", "per year", "by year", "per month", "by month", "growth")
177
+ )
178
+
179
+ single_series = len(series) == 1
180
+ if single_series and len(labels) <= PIE_MAX_ROWS and (proportion_intent or trend_intent is False):
181
+ chart_type = "pie"
182
+ elif trend_intent:
183
+ chart_type = "line"
184
+ elif single_series and len(labels) <= PIE_MAX_ROWS and len(rows) <= PIE_MAX_ROWS:
185
+ chart_type = "pie"
186
+ else:
187
+ chart_type = "bar"
188
+
189
+ title = (question or "").strip().rstrip("?").strip()
190
+ if len(title) > 80:
191
+ title = title[:79] + "…"
192
+
193
+ return {
194
+ "type": chart_type,
195
+ "title": title or "Query result",
196
+ "xlabel": _nice_series_name(label_col),
197
+ "ylabel": series[0]["name"] if single_series else "value",
198
+ "x": labels,
199
+ "series": series,
200
+ "rows_in_result": len(rows),
201
+ }
202
+
203
+
204
+ # ---------------------------------------------------------------------------
205
+ # Embedding / extraction
206
+ # ---------------------------------------------------------------------------
207
+ def embed_chart_marker(answer_text: str, spec: Optional[Dict[str, Any]]) -> str:
208
+ """Append the chart marker to an answer. Safe to call with spec=None."""
209
+ if not spec:
210
+ return answer_text
211
+ try:
212
+ payload = json.dumps(spec, ensure_ascii=False, separators=(",", ":"), default=str)
213
+ except (TypeError, ValueError):
214
+ return answer_text
215
+ return f"{answer_text}\n{CHART_OPEN}{payload}{CHART_CLOSE}"
216
+
217
+
218
+ def extract_chart_marker(text: Optional[str]) -> Tuple[Optional[str], Optional[Dict[str, Any]]]:
219
+ """Split an answer into (clean_text, chart_spec|None).
220
+
221
+ Never throws; on malformed payloads the marker text is left in the answer
222
+ if extraction fails (chart simply won't render).
223
+ """
224
+ if not text or CHART_OPEN not in text:
225
+ return text, None
226
+ head, rest = text.split(CHART_OPEN, 1)
227
+ if CHART_CLOSE not in rest:
228
+ return text, None
229
+ payload, tail = rest.split(CHART_CLOSE, 1)
230
+ clean = (head.rstrip() + ("\n" + tail.strip() if tail.strip() else "")).strip()
231
+ try:
232
+ spec = json.loads(payload)
233
+ if isinstance(spec, dict) and spec.get("type") in ("pie", "bar", "line") and spec.get("series"):
234
+ return clean, spec
235
+ except (ValueError, TypeError):
236
+ pass
237
+ return text, None
Agent/invariants.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Invariant classification and enforcement for text2sql without hardcoded SQL templates.
2
+
3
+ All regeneration remains purely LLM-driven. We only express semantic/structural
4
+ constraints ("invariants") and ask the model to satisfy missing ones.
5
+
6
+ Categories:
7
+ MANAGER_LIST -> list current department managers
8
+ DEPARTMENT_LIST -> list department names
9
+ AVG_SALARY_BY_DEPT -> average current salary per department
10
+ TITLE_COUNT -> count employees with a given title (e.g. Senior Engineer)
11
+ GENERIC -> anything else (no special invariants)
12
+
13
+ Each invariant is represented as a dict:
14
+ {
15
+ 'name': short identifier,
16
+ 'description': human-readable guidance,
17
+ 'check': callable(sql:str)->bool
18
+ }
19
+
20
+ We DO NOT inject SQL fragments. We only:
21
+ - detect which invariants fail
22
+ - compile a focused regeneration prompt listing just the missing invariants
23
+ - request a corrected SQL (single statement ending with semicolon + LIMIT 100)
24
+
25
+ This preserves the "no hardcoded fallback query" policy.
26
+ """
27
+ from __future__ import annotations
28
+ import os
29
+ import re
30
+ from typing import List, Dict, Callable, Optional
31
+
32
+ CATEGORY_MANAGER_LIST = "MANAGER_LIST"
33
+ CATEGORY_DEPT_LIST = "DEPARTMENT_LIST"
34
+ CATEGORY_AVG_SALARY = "AVG_SALARY_BY_DEPT"
35
+ CATEGORY_TITLE_COUNT = "TITLE_COUNT"
36
+ CATEGORY_EMP_COUNT_BY_DEPT = "EMP_COUNT_BY_DEPT"
37
+ CATEGORY_GENERIC = "GENERIC"
38
+
39
+ # Newly added categories (extended taxonomy)
40
+ CATEGORY_SIMPLE_COUNT_EMP = "SIMPLE_COUNT_EMP"
41
+ CATEGORY_SIMPLE_COUNT_EMP_CURRENT = "SIMPLE_COUNT_EMP_CURRENT"
42
+ CATEGORY_SIMPLE_COUNT_DEPT = "SIMPLE_COUNT_DEPT"
43
+ CATEGORY_SALARY_EXTREMES_GLOBAL = "SALARY_EXTREMES_GLOBAL"
44
+ CATEGORY_SALARY_RANGE_BY_DEPT = "SALARY_RANGE_BY_DEPT"
45
+ CATEGORY_TOP_N_SALARIES = "TOP_N_SALARIES"
46
+ CATEGORY_DEPT_MANAGER_LIST = "DEPT_MANAGER_LIST" # dept + manager names
47
+ CATEGORY_MANAGER_TENURE = "MANAGER_TENURE"
48
+ CATEGORY_MANAGER_CHANGE_FREQUENCY = "MANAGER_CHANGE_FREQUENCY"
49
+ CATEGORY_TITLE_DISTINCT_COUNT = "TITLE_DISTINCT_COUNT"
50
+ CATEGORY_TITLE_SPECIFIC_COUNT = "TITLE_SPECIFIC_COUNT"
51
+ CATEGORY_TITLE_DISTRIBUTION_BY_DEPT = "TITLE_DISTRIBUTION_BY_DEPT"
52
+ CATEGORY_PROMOTION_PATH_ENGINEER_TO_SENIOR = "PROMOTION_PATH_ENGINEER_TO_SENIOR"
53
+ CATEGORY_EMP_TENURE_CURRENT_DEPT = "EMP_TENURE_CURRENT_DEPT"
54
+ CATEGORY_HIRING_TREND_BY_YEAR = "HIRING_TREND_BY_YEAR"
55
+ CATEGORY_SALARY_TREND_BY_YEAR = "SALARY_TREND_BY_YEAR"
56
+ CATEGORY_EMP_DEPT_CHANGES = "EMP_DEPT_CHANGES"
57
+ CATEGORY_GENDER_DIST_BY_DEPT = "GENDER_DIST_BY_DEPT"
58
+ CATEGORY_GENDER_PAY_GAP_BY_DEPT = "GENDER_PAY_GAP_BY_DEPT"
59
+ CATEGORY_FEMALE_MANAGERS_COUNT = "FEMALE_MANAGERS_COUNT"
60
+ CATEGORY_AVG_SALARY_BY_TITLE_AND_DEPT = "AVG_SALARY_BY_TITLE_AND_DEPT"
61
+ CATEGORY_GENDER_MANAGEMENT_COUNT = "GENDER_MANAGEMENT_COUNT"
62
+ CATEGORY_SENIOR_STAFF_SUPERLATIVE = "SENIOR_STAFF_SUPERLATIVE"
63
+
64
+ Category = str
65
+
66
+ # ---------------- Classification -----------------
67
+
68
+ def classify_question(question: str) -> Category:
69
+ q = question.lower()
70
+ # Specific order matters: more specialized patterns first
71
+ if any(k in q for k in ["top", "highest-paid", "highest paid"]) and "salary" in q:
72
+ return CATEGORY_TOP_N_SALARIES
73
+ if any(kw in q for kw in ["total number of employees", "total employees"]) or ("count" in q and "employee" in q and "department" not in q and "current" not in q):
74
+ return CATEGORY_SIMPLE_COUNT_EMP
75
+ if ("how many" in q or "count" in q) and "currently" in q and "employee" in q:
76
+ return CATEGORY_SIMPLE_COUNT_EMP_CURRENT
77
+ if ("how many" in q or "number of" in q or "count" in q) and "departments" in q and "manager" not in q:
78
+ return CATEGORY_SIMPLE_COUNT_DEPT
79
+ if any(w in q for w in ["highest", "lowest"]) and "salary" in q and "department" not in q:
80
+ return CATEGORY_SALARY_EXTREMES_GLOBAL
81
+ if "salary range" in q and "department" in q:
82
+ return CATEGORY_SALARY_RANGE_BY_DEPT
83
+ if "most employees" in q and "department" in q:
84
+ return CATEGORY_EMP_COUNT_BY_DEPT
85
+ if "highest average salary" in q and "department" in q:
86
+ return CATEGORY_AVG_SALARY
87
+ if any(k in q for k in ["manager", "managers"]) and "department" in q:
88
+ if "tenure" in q or "long" in q or "position" in q:
89
+ return CATEGORY_MANAGER_TENURE
90
+ if "changed" in q or "changes" in q or "frequently" in q:
91
+ return CATEGORY_MANAGER_CHANGE_FREQUENCY
92
+ if "list" in q and "manager" in q and "department" in q:
93
+ return CATEGORY_DEPT_MANAGER_LIST
94
+ return CATEGORY_MANAGER_LIST
95
+ if ("how many" in q or "count" in q) and "job title" in q and ("exist" in q or "different" in q):
96
+ return CATEGORY_TITLE_DISTINCT_COUNT
97
+ if ("how many" in q or "count" in q) and any(t in q for t in ["senior engineer", "senior engineers"]):
98
+ return CATEGORY_TITLE_SPECIFIC_COUNT
99
+ if "distribution" in q and "title" in q and "department" in q:
100
+ return CATEGORY_TITLE_DISTRIBUTION_BY_DEPT
101
+ if "promoted" in q and "engineer" in q and "senior engineer" in q:
102
+ return CATEGORY_PROMOTION_PATH_ENGINEER_TO_SENIOR
103
+ if ("how long" in q or "tenure" in q) and "current" in q and "department" in q and "employee" in q:
104
+ return CATEGORY_EMP_TENURE_CURRENT_DEPT
105
+ if ("hiring trend" in q) or ("hire" in q and "year" in q):
106
+ return CATEGORY_HIRING_TREND_BY_YEAR
107
+ if ("salaries" in q or "salary" in q) and "changed" in q and ("over time" in q or "year" in q):
108
+ return CATEGORY_SALARY_TREND_BY_YEAR
109
+ if "changed departments" in q or ("employees" in q and "changed" in q and "department" in q):
110
+ return CATEGORY_EMP_DEPT_CHANGES
111
+ if "gender distribution" in q and "department" in q:
112
+ return CATEGORY_GENDER_DIST_BY_DEPT
113
+ if "gender pay gap" in q and "department" in q:
114
+ return CATEGORY_GENDER_PAY_GAP_BY_DEPT
115
+ if ("female" in q and "manager" in q and ("how many" in q or "count" in q)):
116
+ return CATEGORY_FEMALE_MANAGERS_COUNT
117
+ if "average salary" in q and "title" in q and "department" in q:
118
+ return CATEGORY_AVG_SALARY_BY_TITLE_AND_DEPT
119
+ if ("gender" in q and "management" in q) or ("each gender" in q and "management" in q):
120
+ return CATEGORY_GENDER_MANAGEMENT_COUNT
121
+ if ("most" in q and "senior" in q and "staff" in q) or ("senior staff" in q and "most" in q):
122
+ return CATEGORY_SENIOR_STAFF_SUPERLATIVE
123
+ if any(k in q for k in ["list departments", "department names", "department name", "departments list"]):
124
+ return CATEGORY_DEPT_LIST
125
+ if "average" in q and "salary" in q and "department" in q:
126
+ return CATEGORY_AVG_SALARY
127
+ if ("count" in q or "how many" in q or "number of" in q) and any(t in q for t in ["engineer", "engineers", "title"]):
128
+ return CATEGORY_TITLE_COUNT
129
+ if ("count" in q or "how many" in q or "number of" in q or any(s in q for s in ["most", "largest", "highest", "fewest", "least"])) and "department" in q and ("employee" in q or "employees" in q):
130
+ return CATEGORY_EMP_COUNT_BY_DEPT
131
+ return CATEGORY_GENERIC
132
+
133
+ # --------------- Invariant Builders ---------------
134
+
135
+ def _regex(pattern: str) -> Callable[[str], bool]:
136
+ rx = re.compile(pattern, re.IGNORECASE)
137
+ return lambda sql: bool(rx.search(sql))
138
+
139
+ def _contains_all(*subs: str) -> Callable[[str], bool]:
140
+ def check(sql: str) -> bool:
141
+ l = sql.lower()
142
+ return all(s.lower() in l for s in subs)
143
+ return check
144
+
145
+ def build_invariants(category: Category, question: str) -> List[Dict[str, any]]:
146
+ inv: List[Dict[str, any]] = []
147
+ if category == CATEGORY_MANAGER_LIST:
148
+ inv += [
149
+ {"name": "has_department_join", "description": "Join department (alias d) with dept_manager (alias dm)", "check": lambda s: re.search(r"join\s+dept_manager", s, re.IGNORECASE) and re.search(r"from\s+department", s, re.IGNORECASE)},
150
+ {"name": "has_employee_join", "description": "Join employee (alias e) for manager names", "check": _regex(r"join\s+employee")},
151
+ {"name": "selects_names", "description": "Select employee first_name and last_name", "check": lambda s: all(x in s.lower() for x in ["first_name", "last_name"])},
152
+ {"name": "filters_current", "description": "Filter current managers dm.to_date='9999-01-01'", "check": _regex(r"dm\.to_date\s*=\s*'9999-01-01'")},
153
+ {"name": "limit_100", "description": "Ends with LIMIT 100 semicolon", "check": _regex(r"limit\s+100;?\s*$")},
154
+ ]
155
+ elif category == CATEGORY_DEPT_LIST:
156
+ inv += [
157
+ {"name": "from_department", "description": "Query FROM department table", "check": _regex(r"from\s+department")},
158
+ {"name": "select_dept_name", "description": "Select dept_name column", "check": _regex(r"dept_name")},
159
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
160
+ ]
161
+ elif category == CATEGORY_AVG_SALARY:
162
+ inv += [
163
+ {"name": "joins_salary", "description": "Join salary s (FROM salary s)", "check": _regex(r"from\s+salary\s+s")},
164
+ {"name": "joins_dept_emp", "description": "Join dept_emp de", "check": _regex(r"join\s+dept_emp")},
165
+ {"name": "joins_department", "description": "Join department d", "check": _regex(r"join\s+department")},
166
+ {"name": "avg_salary", "description": "Uses AVG(s.salary)", "check": _regex(r"avg\s*\(\s*s\.salary\s*\)")},
167
+ {"name": "current_filters", "description": "Filters current rows s.to_date='9999-01-01' and de.to_date='9999-01-01'", "check": lambda s: "s.to_date='9999-01-01'" in s.lower() and "de.to_date='9999-01-01'" in s.lower()},
168
+ {"name": "group_by_dept", "description": "GROUP BY department name", "check": _regex(r"group\s+by\s+.*dept_name")},
169
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
170
+ ]
171
+ elif category == CATEGORY_TITLE_COUNT:
172
+ # Attempt to infer canonical title (not used in invariants; regeneration prompt may hint)
173
+ inv += [
174
+ {"name": "from_title", "description": "FROM title table (alias t)", "check": _regex(r"from\s+title")},
175
+ {"name": "alias_t", "description": "Alias 't' used for title table", "check": _regex(r"from\s+title\s+(?:as\s+)?t")},
176
+ {"name": "current_rows", "description": "Filter current rows t.to_date='9999-01-01'", "check": _regex(r"t\.to_date\s*=\s*'9999-01-01'")},
177
+ {"name": "count_distinct", "description": "COUNT(DISTINCT t.emp_no)", "check": _regex(r"count\s*\(\s*distinct\s+t\.emp_no\s*\)")},
178
+ {"name": "has_title_filter", "description": "Filter on t.title = '<Some Title>'", "check": _regex(r"t\.title\s*=\s*'[^']+'")} ,
179
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
180
+ ]
181
+ elif category == CATEGORY_EMP_COUNT_BY_DEPT:
182
+ inv += [
183
+ {"name": "has_dept_emp_join", "description": "Join dept_emp de with department d", "check": lambda s: re.search(r"join\s+dept_emp", s, re.IGNORECASE) and re.search(r"join\s+department|from\s+department", s, re.IGNORECASE)},
184
+ {"name": "select_dept_name", "description": "Select d.dept_name", "check": _regex(r"d\.dept_name|dept_name")},
185
+ {"name": "select_count", "description": "Include COUNT(*) or COUNT(de.emp_no)", "check": _regex(r"count\s*\(")},
186
+ {"name": "group_by", "description": "GROUP BY d.dept_name present", "check": _regex(r"group\s+by\s+.*dept_name")},
187
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
188
+ {"name": "count_alias", "description": "Provide an explicit alias e.g. COUNT(*) AS employee_count", "check": _regex(r"count\s*\(.*\)\s+as\s+employee_count")},
189
+ ]
190
+ # If the question is superlative-oriented, encourage ordering
191
+ ql = question.lower()
192
+ if any(w in ql for w in ["most", "largest", "highest", "fewest", "least"]):
193
+ inv.append({"name": "order_by_count", "description": "ORDER BY employee_count DESC (or ASC for fewest/least)", "check": lambda s: ("fewest" in ql or "least" in ql and re.search(r"order\s+by\s+employee_count\s+asc", s, re.IGNORECASE)) or re.search(r"order\s+by\s+employee_count\s+desc", s, re.IGNORECASE)})
194
+ elif category == CATEGORY_SIMPLE_COUNT_EMP:
195
+ inv += [
196
+ {"name": "from_employee", "description": "FROM employee table", "check": _regex(r"from\s+employee")},
197
+ {"name": "count_all", "description": "COUNT(*) with alias total_employees", "check": _regex(r"count\s*\(\s*\*\s*\)\s+as\s+total_employees")},
198
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
199
+ ]
200
+ elif category == CATEGORY_SIMPLE_COUNT_EMP_CURRENT:
201
+ inv += [
202
+ {"name": "join_dept_emp", "description": "Join dept_emp de", "check": _regex(r"join\s+dept_emp")},
203
+ {"name": "current_filter", "description": "de.to_date='9999-01-01' filter", "check": _regex(r"de\.to_date\s*=\s*'9999-01-01'")},
204
+ {"name": "count_distinct_emp", "description": "COUNT(DISTINCT de.emp_no) alias current_employee_count", "check": _regex(r"count\s*\(\s*distinct\s+de\.emp_no\s*\)\s+as\s+current_employee_count")},
205
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
206
+ ]
207
+ elif category == CATEGORY_SIMPLE_COUNT_DEPT:
208
+ inv += [
209
+ {"name": "from_department", "description": "FROM department", "check": _regex(r"from\s+department")},
210
+ {"name": "count_depts", "description": "COUNT(*) AS department_count", "check": _regex(r"count\s*\(\s*\*\s*\)\s+as\s+department_count")},
211
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
212
+ ]
213
+ elif category == CATEGORY_SALARY_EXTREMES_GLOBAL:
214
+ # Extremely strict invariants for highest/lowest salary by department
215
+ inv += [
216
+ {"name": "from_salary_s", "description": "FROM salary s", "check": _regex(r"from\s+salary\s+s")},
217
+ {"name": "join_dept_emp_de", "description": "JOIN dept_emp de ON s.emp_no = de.emp_no", "check": _regex(r"join\s+dept_emp\s+de\s+on\s+s\.emp_no\s*=\s*de\.emp_no")},
218
+ {"name": "join_department_d", "description": "JOIN department d ON de.dept_no = d.dept_no", "check": _regex(r"join\s+department\s+d\s+on\s+de\.dept_no\s*=\s*d\.dept_no")},
219
+ {"name": "select_dept_name", "description": "SELECT d.dept_name", "check": _regex(r"select\s+d\.dept_name")},
220
+ {"name": "select_max_min_salary", "description": "SELECT MAX(s.salary) AS highest_salary, MIN(s.salary) AS lowest_salary", "check": lambda s: re.search(r"max\s*\(\s*s\.salary\s*\)\s+as\s+highest_salary", s, re.IGNORECASE) and re.search(r"min\s*\(\s*s\.salary\s*\)\s+as\s+lowest_salary", s, re.IGNORECASE)},
221
+ {"name": "group_by_dept_name", "description": "GROUP BY d.dept_name", "check": _regex(r"group\s+by\s+d\.dept_name")},
222
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
223
+ {"name": "no_unaliased_salary", "description": "Do not use MAX(salary) or MIN(salary) without s. alias", "check": lambda s: not re.search(r"max\s*\(\s*salary\s*\)", s, re.IGNORECASE) and not re.search(r"min\s*\(\s*salary\s*\)", s, re.IGNORECASE)},
224
+ {"name": "no_unaliased_dept_name", "description": "Do not use dept_name without d. alias", "check": lambda s: not re.search(r"[^a-zA-Z0-9_]dept_name", s) or re.search(r"d\.dept_name", s)},
225
+ ]
226
+ elif category == CATEGORY_SALARY_RANGE_BY_DEPT:
227
+ # Stricter invariants for salary range by department
228
+ inv += [
229
+ {"name": "joins_salary", "description": "FROM salary s", "check": _regex(r"from\s+salary\s+s")},
230
+ {"name": "joins_dept_emp", "description": "Join dept_emp de", "check": _regex(r"join\s+dept_emp")},
231
+ {"name": "joins_department", "description": "Join department d", "check": _regex(r"join\s+department")},
232
+ {"name": "select_dept_name", "description": "Select d.dept_name", "check": _regex(r"d\.dept_name")},
233
+ {"name": "min_max", "description": "MIN(s.salary) & MAX(s.salary)", "check": lambda s: re.search(r"min\s*\(\s*s\.salary", s, re.IGNORECASE) and re.search(r"max\s*\(\s*s\.salary", s, re.IGNORECASE)},
234
+ {"name": "dept_filter", "description": "Filter on d.dept_name=...", "check": _regex(r"d\.dept_name\s*=\s*'")},
235
+ {"name": "group_by_dept", "description": "GROUP BY d.dept_name", "check": _regex(r"group\s+by\s+.*d\.dept_name")},
236
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
237
+ ]
238
+ elif category == CATEGORY_TOP_N_SALARIES:
239
+ inv += [
240
+ {"name": "joins_salary", "description": "FROM salary s", "check": _regex(r"from\s+salary\s+s")},
241
+ {"name": "current_filter", "description": "s.to_date='9999-01-01'", "check": _regex(r"s\.to_date\s*=\s*'9999-01-01'")},
242
+ {"name": "order_desc", "description": "ORDER BY s.salary DESC", "check": _regex(r"order\s+by\s+s\.salary\s+desc")},
243
+ {"name": "limit_present", "description": "Has a LIMIT clause", "check": _regex(r"limit\s+\d+")},
244
+ ]
245
+ elif category == CATEGORY_DEPT_MANAGER_LIST:
246
+ inv += [
247
+ {"name": "joins_dept_manager", "description": "Join dept_manager dm", "check": _regex(r"join\s+dept_manager")},
248
+ {"name": "joins_employee", "description": "Join employee e", "check": _regex(r"join\s+employee")},
249
+ {"name": "select_names", "description": "Select manager first_name / last_name", "check": lambda s: "first_name" in s.lower() and "last_name" in s.lower()},
250
+ {"name": "dept_name", "description": "Select dept_name", "check": _regex(r"dept_name")},
251
+ {"name": "current_filter", "description": "dm.to_date='9999-01-01'", "check": _regex(r"dm\.to_date\s*=\s*'9999-01-01'")},
252
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
253
+ ]
254
+ elif category == CATEGORY_MANAGER_TENURE:
255
+ inv += [
256
+ {"name": "joins_dept_manager", "description": "Join dept_manager dm", "check": _regex(r"join\s+dept_manager")},
257
+ {"name": "current_filter", "description": "dm.to_date='9999-01-01'", "check": _regex(r"dm\.to_date\s*=\s*'9999-01-01'")},
258
+ {"name": "tenure_expr", "description": "Contains dm.from_date for tenure calc", "check": _regex(r"dm\.from_date")},
259
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
260
+ ]
261
+ elif category == CATEGORY_MANAGER_CHANGE_FREQUENCY:
262
+ inv += [
263
+ {"name": "from_dept_manager", "description": "FROM dept_manager", "check": _regex(r"from\s+dept_manager")},
264
+ {"name": "group_by_dept", "description": "GROUP BY dept_no or dept", "check": _regex(r"group\s+by\s+.*dept")},
265
+ {"name": "count_changes", "description": "COUNT(*) or COUNT(DISTINCT emp_no)", "check": _regex(r"count\s*\(")},
266
+ {"name": "order_desc", "description": "ORDER BY count desc", "check": _regex(r"order\s+by\s+.*count.*desc")},
267
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
268
+ ]
269
+ elif category == CATEGORY_TITLE_DISTINCT_COUNT:
270
+ inv += [
271
+ {"name": "from_title", "description": "FROM title t", "check": _regex(r"from\s+title")},
272
+ {"name": "count_distinct_titles", "description": "COUNT(DISTINCT t.title) alias title_count", "check": _regex(r"count\s*\(\s*distinct\s+t\.title\s*\)\s+as\s+title_count")},
273
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
274
+ ]
275
+ elif category == CATEGORY_TITLE_SPECIFIC_COUNT:
276
+ inv += [
277
+ {"name": "from_title", "description": "FROM title t", "check": _regex(r"from\s+title")},
278
+ {"name": "title_filter", "description": "Filter t.title='Senior Engineer'", "check": _regex(r"t\.title\s*=\s*'senior engineer'")},
279
+ {"name": "current_filter", "description": "t.to_date='9999-01-01'", "check": _regex(r"t\.to_date\s*=\s*'9999-01-01'")},
280
+ {"name": "count_distinct_emp", "description": "COUNT(DISTINCT t.emp_no)", "check": _regex(r"count\s*\(\s*distinct\s+t\.emp_no")},
281
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
282
+ ]
283
+ elif category == CATEGORY_TITLE_DISTRIBUTION_BY_DEPT:
284
+ inv += [
285
+ {"name": "joins_title", "description": "Join title t", "check": _regex(r"join\s+title")},
286
+ {"name": "joins_dept_emp", "description": "Join dept_emp de", "check": _regex(r"join\s+dept_emp")},
287
+ {"name": "joins_department", "description": "Join department d", "check": _regex(r"join\s+department")},
288
+ {"name": "current_filters", "description": "t.to_date & de.to_date current filters", "check": lambda s: "t.to_date='9999-01-01'" in s.lower() and "de.to_date='9999-01-01'" in s.lower()},
289
+ {"name": "group_by", "description": "GROUP BY dept and title", "check": _regex(r"group\s+by\s+.*(dept|title).*(title|dept)")},
290
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
291
+ ]
292
+ elif category == CATEGORY_PROMOTION_PATH_ENGINEER_TO_SENIOR:
293
+ inv += [
294
+ {"name": "dual_title_refs", "description": "References title table twice (t1, t2)", "check": _regex(r"title\s+t1.*title\s+t2|title\s+t2.*title\s+t1")},
295
+ {"name": "promotion_condition", "description": "t1.title='Engineer' AND t2.title='Senior Engineer'", "check": _regex(r"t1\.title\s*=\s*'engineer'.*t2\.title\s*=\s*'senior engineer'|t2\.title\s*=\s*'senior engineer'.*t1\.title\s*=\s*'engineer'")},
296
+ {"name": "temporal_order", "description": "t1.from_date < t2.from_date", "check": _regex(r"t1\.from_date\s*<\s*t2\.from_date")},
297
+ {"name": "distinct_emp", "description": "DISTINCT emp_no selected", "check": _regex(r"select\s+distinct\s+t1\.emp_no|select\s+distinct\s+t2\.emp_no")},
298
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
299
+ ]
300
+ elif category == CATEGORY_EMP_TENURE_CURRENT_DEPT:
301
+ inv += [
302
+ {"name": "joins_dept_emp", "description": "FROM dept_emp de", "check": _regex(r"from\s+dept_emp")},
303
+ {"name": "current_filter", "description": "de.to_date='9999-01-01'", "check": _regex(r"de\.to_date\s*=\s*'9999-01-01'")},
304
+ {"name": "tenure_expr", "description": "Uses de.from_date", "check": _regex(r"de\.from_date")},
305
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
306
+ ]
307
+ elif category == CATEGORY_HIRING_TREND_BY_YEAR:
308
+ inv += [
309
+ {"name": "from_employee", "description": "FROM employee e", "check": _regex(r"from\s+employee")},
310
+ {"name": "year_extract", "description": "EXTRACT(YEAR FROM hire_date)", "check": _regex(r"extract\s*\(\s*year\s+from\s+.*hire_date")},
311
+ {"name": "group_by_year", "description": "GROUP BY year", "check": _regex(r"group\s+by\s+.*year")},
312
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
313
+ ]
314
+ elif category == CATEGORY_SALARY_TREND_BY_YEAR:
315
+ inv += [
316
+ {"name": "from_salary", "description": "FROM salary s", "check": _regex(r"from\s+salary")},
317
+ {"name": "year_extract", "description": "EXTRACT(YEAR FROM s.from_date)", "check": _regex(r"extract\s*\(\s*year\s+from\s+s\.from_date")},
318
+ {"name": "avg_salary", "description": "AVG(s.salary)", "check": _regex(r"avg\s*\(\s*s\.salary")},
319
+ {"name": "group_by_year", "description": "GROUP BY year", "check": _regex(r"group\s+by\s+.*year")},
320
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
321
+ ]
322
+ elif category == CATEGORY_EMP_DEPT_CHANGES:
323
+ inv += [
324
+ {"name": "from_dept_emp", "description": "FROM dept_emp de", "check": _regex(r"from\s+dept_emp")},
325
+ {"name": "group_by_emp", "description": "GROUP BY de.emp_no", "check": _regex(r"group\s+by\s+.*emp_no")},
326
+ {"name": "having_multiple", "description": "HAVING COUNT(DISTINCT dept_no) > 1", "check": _regex(r"having\s+count\s*\(\s*distinct\s+dept_no\s*\)\s*>\s*1")},
327
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
328
+ ]
329
+ elif category == CATEGORY_GENDER_DIST_BY_DEPT:
330
+ inv += [
331
+ {"name": "joins_employee", "description": "Join employee e", "check": _regex(r"join\s+employee")},
332
+ {"name": "joins_dept_emp", "description": "Join dept_emp de", "check": _regex(r"join\s+dept_emp")},
333
+ {"name": "joins_department", "description": "Join department d", "check": _regex(r"join\s+department")},
334
+ {"name": "current_filter", "description": "de.to_date='9999-01-01'", "check": _regex(r"de\.to_date\s*=\s*'9999-01-01'")},
335
+ {"name": "group_by_dept_gender", "description": "GROUP BY dept & gender", "check": _regex(r"group\s+by\s+.*(dept|gender).*(gender|dept)")},
336
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
337
+ ]
338
+ elif category == CATEGORY_GENDER_PAY_GAP_BY_DEPT:
339
+ inv += [
340
+ {"name": "joins_salary", "description": "Join salary s", "check": _regex(r"join\s+salary")},
341
+ {"name": "joins_employee", "description": "Join employee e", "check": _regex(r"join\s+employee")},
342
+ {"name": "joins_dept_emp", "description": "Join dept_emp de", "check": _regex(r"join\s+dept_emp")},
343
+ {"name": "joins_department", "description": "Join department d", "check": _regex(r"join\s+department")},
344
+ {"name": "current_filters", "description": "Current rows s.to_date & de.to_date", "check": lambda s: "s.to_date='9999-01-01'" in s.lower() and "de.to_date='9999-01-01'" in s.lower()},
345
+ {"name": "avg_salary", "description": "AVG(s.salary)", "check": _regex(r"avg\s*\(\s*s\.salary")},
346
+ {"name": "group_by_dept_gender", "description": "GROUP BY dept & gender", "check": _regex(r"group\s+by\s+.*(dept|gender).*(gender|dept)")},
347
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
348
+ ]
349
+ elif category == CATEGORY_FEMALE_MANAGERS_COUNT:
350
+ inv += [
351
+ {"name": "joins_dept_manager", "description": "Join dept_manager dm", "check": _regex(r"join\s+dept_manager")},
352
+ {"name": "joins_employee", "description": "Join employee e", "check": _regex(r"join\s+employee")},
353
+ {"name": "female_filter", "description": "e.gender='F'", "check": _regex(r"e\.gender\s*=\s*'f'")},
354
+ {"name": "current_filter", "description": "dm.to_date='9999-01-01'", "check": _regex(r"dm\.to_date\s*=\s*'9999-01-01'")},
355
+ {"name": "count_distinct_mgr", "description": "COUNT(DISTINCT dm.emp_no)", "check": _regex(r"count\s*\(\s*distinct\s+dm\.emp_no")},
356
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
357
+ ]
358
+ elif category == CATEGORY_AVG_SALARY_BY_TITLE_AND_DEPT:
359
+ inv += [
360
+ {"name": "joins_salary", "description": "Join salary s", "check": _regex(r"join\s+salary")},
361
+ {"name": "joins_title", "description": "Join title t", "check": _regex(r"join\s+title")},
362
+ {"name": "joins_dept_emp", "description": "Join dept_emp de", "check": _regex(r"join\s+dept_emp")},
363
+ {"name": "joins_department", "description": "Join department d", "check": _regex(r"join\s+department")},
364
+ {"name": "current_filters", "description": "Current rows for s,de,t", "check": lambda s: all(x in s.lower() for x in ["s.to_date='9999-01-01'", "de.to_date='9999-01-01'", "t.to_date='9999-01-01'"])},
365
+ {"name": "avg_salary", "description": "AVG(s.salary)", "check": _regex(r"avg\s*\(\s*s\.salary")},
366
+ {"name": "group_by", "description": "GROUP BY dept & title", "check": _regex(r"group\s+by\s+.*(dept|title).*(title|dept)")},
367
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
368
+ ]
369
+ elif category == CATEGORY_GENDER_MANAGEMENT_COUNT:
370
+ inv += [
371
+ {"name": "joins_dept_manager", "description": "Join dept_manager dm", "check": _regex(r"join\s+dept_manager")},
372
+ {"name": "joins_employee", "description": "Join employee e", "check": _regex(r"join\s+employee")},
373
+ {"name": "current_filter", "description": "dm.to_date='9999-01-01'", "check": _regex(r"dm\.to_date\s*=\s*'9999-01-01'")},
374
+ {"name": "group_by_gender", "description": "GROUP BY gender", "check": _regex(r"group\s+by\s+.*gender")},
375
+ {"name": "count_mgr", "description": "COUNT(*) or COUNT(dm.emp_no)", "check": _regex(r"count\s*\(")},
376
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
377
+ ]
378
+ elif category == CATEGORY_SENIOR_STAFF_SUPERLATIVE:
379
+ inv += [
380
+ {"name": "joins_title", "description": "Join title t", "check": _regex(r"join\s+title")},
381
+ {"name": "joins_dept_emp", "description": "Join dept_emp de", "check": _regex(r"join\s+dept_emp")},
382
+ {"name": "joins_department", "description": "Join department d", "check": _regex(r"join\s+department")},
383
+ {"name": "senior_filter", "description": "t.title LIKE 'Senior%'", "check": _regex(r"t\.title\s+like\s+'senior%'")},
384
+ {"name": "current_filters", "description": "Current rows de.to_date & t.to_date", "check": lambda s: "de.to_date='9999-01-01'" in s.lower() and "t.to_date='9999-01-01'" in s.lower()},
385
+ {"name": "group_by_dept", "description": "GROUP BY d.dept_name", "check": _regex(r"group\s+by\s+.*dept_name")},
386
+ {"name": "order_desc", "description": "ORDER BY count desc", "check": _regex(r"order\s+by\s+.*count.*desc")},
387
+ {"name": "limit_100", "description": "Ends with LIMIT 100", "check": _regex(r"limit\s+100;?\s*$")},
388
+ ]
389
+ return inv
390
+
391
+ # --------------- Enforcement -----------------
392
+
393
+ def evaluate_invariants(sql: str, invariants: List[Dict[str, any]]) -> List[Dict[str, any]]:
394
+ failures = []
395
+ for inv in invariants:
396
+ try:
397
+ ok = inv['check'](sql)
398
+ except Exception:
399
+ ok = False
400
+ if not ok:
401
+ failures.append(inv)
402
+ return failures
403
+
404
+
405
+ # More explicit prompt for join-based salary extremes queries
406
+ REGEN_PROMPT_TEMPLATE = (
407
+ "You produced SQL for the user question. Some required invariants are missing.\n"
408
+ "Regenerate a SINGLE valid PostgreSQL SQL query that satisfies ALL listed invariants.\n"
409
+ "Return ONLY the SQL (no commentary). Must end with LIMIT 100; and a semicolon.\n"
410
+ "If the question is about highest/lowest salary by department, you MUST:\n"
411
+ "- Use FROM salary s\n"
412
+ "- JOIN dept_emp de ON s.emp_no = de.emp_no\n"
413
+ "- JOIN department d ON de.dept_no = d.dept_no\n"
414
+ "- SELECT d.dept_name, MAX(s.salary) AS highest_salary, MIN(s.salary) AS lowest_salary\n"
415
+ "- GROUP BY d.dept_name\n"
416
+ "- Use correct table aliases everywhere (no unaliased salary or dept_name)\n"
417
+ "- Do NOT reference columns that do not exist in the schema\n"
418
+ "User Question: {question}\n"
419
+ "Previous Attempt: {previous_sql}\n"
420
+ "Missing Invariants:\n{invariant_lines}\n"
421
+ "Regenerate now:"
422
+ )
423
+
424
+
425
+ def regenerate_with_constraints(question: str, previous_sql: str, missing: List[Dict[str, any]], llm, run_llm_fn, attempt: int) -> Optional[str]:
426
+ invariant_lines = "\n".join(f"- {m['name']}: {m['description']}" for m in missing)
427
+ prompt = REGEN_PROMPT_TEMPLATE.format(question=question, previous_sql=previous_sql, invariant_lines=invariant_lines)
428
+ # Use proper timeout values instead of hardcoded ones
429
+ # Start with a good timeout and decrease gradually for subsequent attempts
430
+ base_timeout = float(os.environ.get("INVARIANTS_BASE_TIMEOUT", 90)) # Start with 90s
431
+ timeout = max(30.0, base_timeout - attempt * 20.0) # Decrease by 20s per attempt, minimum 30s
432
+ try:
433
+ raw = run_llm_fn(llm, prompt, timeout=max(8.0, timeout), retries=0)
434
+ # Normalize raw response to text
435
+ raw_text = getattr(raw, 'text', None)
436
+ if raw_text is None:
437
+ raw_text = str(raw)
438
+ # Extract first SELECT ... ;
439
+ m = re.search(r"(SELECT[\s\S]+?;)", raw_text, flags=re.IGNORECASE)
440
+ candidate = m.group(1) if m else raw_text.strip()
441
+ # Clean markdown fences
442
+ candidate = re.sub(r"```(?:sql)?|```", "", candidate, flags=re.IGNORECASE).strip()
443
+ # Ensure single statement & required LIMIT 100 at end
444
+ # Collapse accidental mid-statement semicolon before LIMIT
445
+ candidate = re.sub(r";\s*(LIMIT\s+\d+)", r" \1", candidate, flags=re.IGNORECASE)
446
+ # Append LIMIT 100 if missing (invariants will still verify)
447
+ if 'limit' not in candidate.lower():
448
+ if candidate.endswith(';'):
449
+ candidate = candidate[:-1] + ' LIMIT 100;'
450
+ else:
451
+ candidate += ' LIMIT 100;'
452
+ # Guarantee trailing semicolon
453
+ if not candidate.strip().endswith(';'):
454
+ candidate += ';'
455
+ return candidate
456
+ except Exception as e:
457
+ print(f"[INVARIANTS] Regeneration failed: {e}")
458
+ return None
459
+
460
+
461
+ def enforce_invariants(question: str, sql: str, llm, run_llm_fn, max_regen: int = 2) -> Dict[str, any]:
462
+ category = classify_question(question)
463
+ if category == CATEGORY_GENERIC:
464
+ return {"category": category, "final_sql": sql, "regenerations": []}
465
+ # Dynamic schema support: the invariant catalog is purpose-built for the
466
+ # employee demo schema. For any other database, enforcement is bypassed
467
+ # and only the generic structural validation pipeline applies.
468
+ try:
469
+ try:
470
+ from .agentic_workflow import ACTIVE_SCHEMA_PROFILE as _asp
471
+ except Exception:
472
+ import Agent.agentic_workflow as _aw
473
+ _asp = getattr(_aw, "ACTIVE_SCHEMA_PROFILE", None)
474
+ if _asp is not None and not getattr(_asp, "is_employee_db", True):
475
+ print(f"[INVARIANTS] Bypassed for non-employee schema '{getattr(_asp, 'name', '?')}' (category={category})")
476
+ return {"category": CATEGORY_GENERIC, "final_sql": sql, "regenerations": []}
477
+ except Exception:
478
+ pass # Profile unavailable — default legacy behavior (enforce)
479
+ invariants = build_invariants(category, question)
480
+ regenerations = []
481
+ current_sql = sql
482
+ # Increase max_regen to 5 for more LLM attempts
483
+ for attempt in range(max_regen + 4):
484
+ missing = evaluate_invariants(current_sql, invariants)
485
+ if not missing:
486
+ return {"category": category, "final_sql": current_sql, "regenerations": regenerations}
487
+ if attempt == max_regen:
488
+ # Give up, return last with missing list for transparency
489
+ return {"category": category, "final_sql": current_sql, "regenerations": regenerations, "remaining_missing": [m['name'] for m in missing]}
490
+ regen_sql = regenerate_with_constraints(question, current_sql, missing, llm, run_llm_fn, attempt)
491
+ if not regen_sql:
492
+ return {"category": category, "final_sql": current_sql, "regenerations": regenerations, "remaining_missing": [m['name'] for m in missing]}
493
+ regenerations.append({
494
+ "attempt": attempt + 1,
495
+ "missing_before": [m['name'] for m in missing],
496
+ "sql": regen_sql
497
+ })
498
+ current_sql = regen_sql
499
+ return {"category": category, "final_sql": current_sql, "regenerations": regenerations}
Agent/llm_health_check.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, time, json, sys
2
+ from llama_index.llms.ollama import Ollama
3
+
4
+ BASE_URL = os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434")
5
+ MODEL = os.environ.get("FINETUNED_MODEL_NAME") or os.environ.get("OLLAMA_MODEL_NAME", "gemma3:1b")
6
+
7
+ print(f"Checking Ollama LLM connectivity: base_url={BASE_URL} model={MODEL}")
8
+
9
+ # Lightweight client check without llama_index first (raw HTTP) to see if daemon responds
10
+ try:
11
+ import requests
12
+ r = requests.get(f"{BASE_URL.rstrip('/')}/api/tags", timeout=5)
13
+ print(f"/api/tags status: {r.status_code}")
14
+ if r.ok:
15
+ tags = r.json().get('models', [])
16
+ names = [m.get('name') for m in tags]
17
+ print(f"Available models: {names}")
18
+ if MODEL not in names:
19
+ print(f"Model '{MODEL}' not yet pulled. Run: ollama pull {MODEL}")
20
+ else:
21
+ print("Non-200 response from Ollama daemon")
22
+ except Exception as e:
23
+ print(f"Raw HTTP check failed: {e}")
24
+
25
+ # LlamaIndex call
26
+ try:
27
+ llm = Ollama(model=MODEL, base_url=BASE_URL, temperature=0.1, request_timeout=30)
28
+ t0 = time.time()
29
+ resp = llm.complete(prompt="SELECT 1;")
30
+ dt = time.time() - t0
31
+ print(f"LLM call success in {dt:.2f}s. Raw text: {resp.text[:120]!r}")
32
+ except Exception as e:
33
+ print(f"LLM complete() failed: {type(e).__name__}: {e}")
34
+ sys.exit(1)
35
+
36
+ print("Health check finished.")
Agent/mcp_client.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal MCP client for local MCP server.
2
+
3
+ Provides mcp_complete(prompt, timeout, context) -> str
4
+ Tries to POST to MCP server and return the completion text. Raises on errors so caller can fallback.
5
+ """
6
+ import os
7
+ import json
8
+ import requests
9
+ from typing import Any, Dict, Optional
10
+
11
+ MCP_URL = os.environ.get("MCP_URL", "http://127.0.0.1:8701/complete")
12
+
13
+
14
+ def mcp_complete(prompt: str, timeout: float = 30.0, context: Optional[Dict[str, Any]] = None) -> str:
15
+ """Send a completion request to the local MCP server and return text.
16
+
17
+ Raises requests.RequestException on transport errors or ValueError if MCP returns error.
18
+ """
19
+ payload = {
20
+ "prompt": prompt,
21
+ "context": context or {},
22
+ "timeout": timeout
23
+ }
24
+ headers = {"Content-Type": "application/json"}
25
+ resp = requests.post(MCP_URL, data=json.dumps(payload), headers=headers, timeout=timeout)
26
+ resp.raise_for_status()
27
+ body = resp.json()
28
+ # Expecting {'text': '...'} from MCP server
29
+ if not isinstance(body, dict) or 'text' not in body:
30
+ raise ValueError(f"Unexpected MCP response: {body}")
31
+ return body['text']
32
+
33
+
34
+ def mcp_call_tool(prompt: str, timeout: float = 60.0, context: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
35
+ """Call the MCP /complete endpoint and return the full JSON response.
36
+
37
+ This is useful when asking MCP to run a registered tool; the tool result will
38
+ appear under the `tool_result` key in the returned dict.
39
+ """
40
+ payload = {
41
+ "prompt": prompt,
42
+ "context": context or {},
43
+ "timeout": timeout,
44
+ }
45
+ headers = {"Content-Type": "application/json"}
46
+ resp = requests.post(MCP_URL, data=json.dumps(payload), headers=headers, timeout=timeout)
47
+ resp.raise_for_status()
48
+ return resp.json()
Agent/mcp_server.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ from typing import Any, Dict, Optional, List
4
+ import asyncio
5
+ import importlib
6
+ import uuid
7
+ import os
8
+ import re
9
+
10
+ # Attempt to import agent workflow for schema/inspector & utilities (optional)
11
+ try:
12
+ import Agent.agentic_workflow as aw
13
+ print(f"[MCP STARTUP] Successfully imported Agent.agentic_workflow")
14
+ except Exception as e:
15
+ print(f"[MCP STARTUP] Failed to import Agent.agentic_workflow: {e}")
16
+ aw = None
17
+
18
+ app = FastAPI(title="Minimal MCP Server (dev)")
19
+
20
+ # Simple tool registry
21
+ TOOLS: Dict[str, Any] = {}
22
+
23
+
24
+ class CompleteRequest(BaseModel):
25
+ prompt: str
26
+ context: Optional[Dict[str, Any]] = None
27
+ timeout: Optional[float] = 30.0
28
+
29
+
30
+ def register_tool(name: str, fn: Any):
31
+ TOOLS[name] = fn
32
+
33
+
34
+ async def _call_tool(name: str, args: Dict[str, Any]) -> Any:
35
+ if name not in TOOLS:
36
+ raise KeyError(f"Tool '{name}' not registered")
37
+ fn = TOOLS[name]
38
+ if asyncio.iscoroutinefunction(fn):
39
+ return await fn(**(args or {}))
40
+ else:
41
+ # run sync in threadpool
42
+ loop = asyncio.get_running_loop()
43
+ return await loop.run_in_executor(None, lambda: fn(**(args or {})))
44
+
45
+
46
+ @app.on_event("startup")
47
+ async def _startup():
48
+ # Register built-in/mock tools lazily to avoid importing heavy modules at import time
49
+ # Try to register a real document scanner implementation; otherwise register a mock
50
+ ds_registered = None
51
+ try:
52
+ from .tools import document_scanner as ds
53
+ register_tool("document_scanner.process", ds.process_image)
54
+ ds_registered = f"Agent.tools.document_scanner.process_image (relative import)"
55
+ except Exception:
56
+ # If relative import fails (running as script), try absolute import
57
+ try:
58
+ import Agent.tools.document_scanner as ds2
59
+ register_tool("document_scanner.process", ds2.process_image)
60
+ ds_registered = f"Agent.tools.document_scanner.process_image (absolute import)"
61
+ except Exception:
62
+ # Register a fallback mock tool
63
+ def _mock_doc(**kwargs):
64
+ # Accept arbitrary keyword args (image_url, image_bytes, etc.) to be tolerant
65
+ return {"doc_id": str(uuid.uuid4()), "text": "(mock OCR output)", "metadata": {"pages": 1, "confidence": 0.0}, "received_args": kwargs}
66
+ register_tool("document_scanner.process", _mock_doc)
67
+ ds_registered = "mock(document_scanner.process)"
68
+
69
+ # Log which document scanner implementation was registered for easier debugging
70
+ try:
71
+ print(f"[MCP STARTUP] Registered document_scanner.process -> {ds_registered}")
72
+ except Exception:
73
+ pass
74
+
75
+ # Optional Groq Vision health check in cloud mode
76
+ try:
77
+ from .tools import groq_vision_health
78
+ hc = groq_vision_health.health_check()
79
+ if not hc.get("ok", True):
80
+ print(f"[MCP STARTUP] Groq Vision health warning: {hc.get('error')} (model={hc.get('model')})")
81
+ else:
82
+ print(f"[MCP STARTUP] Groq Vision health: ok (model={hc.get('model')})")
83
+ except Exception as e:
84
+ print(f"[MCP STARTUP] Groq Vision health check skipped: {e}")
85
+
86
+ # Register Granite Vision direct visual Q&A tool
87
+ gv_registered = None
88
+ try:
89
+ from .tools import granite_vision as gv
90
+ register_tool("granite_vision.qa", gv.qa)
91
+ gv_registered = "Agent.tools.granite_vision.qa (relative import)"
92
+ except Exception as e1:
93
+ print(f"[MCP STARTUP] granite_vision relative import FAILED: {type(e1).__name__}: {e1}")
94
+ try:
95
+ import Agent.tools.granite_vision as gv2
96
+ register_tool("granite_vision.qa", gv2.qa)
97
+ gv_registered = "Agent.tools.granite_vision.qa (absolute import)"
98
+ except Exception as e2:
99
+ print(f"[MCP STARTUP] granite_vision absolute import FAILED: {type(e2).__name__}: {e2}")
100
+ def _mock_gv(**kwargs):
101
+ return {"answer": "(granite_vision unavailable - mock)", "model": "mock", "received_args": kwargs}
102
+ register_tool("granite_vision.qa", _mock_gv)
103
+ gv_registered = "mock(granite_vision.qa)"
104
+ print(f"[MCP STARTUP] Registered granite_vision.qa -> {gv_registered}")
105
+
106
+
107
+ # Register OCR QA composite tool: runs OCR then runs the agent OCR QA helper
108
+ try:
109
+ # Use the global aw variable instead of re-importing
110
+ if not aw:
111
+ raise ImportError("Agent workflow not available")
112
+
113
+ async def _ocr_qa_tool(image_url: Optional[str] = None, image_bytes: Optional[bytes] = None, question: Optional[str] = None, **kwargs):
114
+ # Call the document scanner tool first (use the registered one to allow mocks)
115
+ ds_fn = TOOLS.get("document_scanner.process")
116
+ if not ds_fn:
117
+ raise RuntimeError("document_scanner.process not registered")
118
+
119
+ loop = asyncio.get_running_loop()
120
+ try:
121
+ if asyncio.iscoroutinefunction(ds_fn):
122
+ tool_res = await ds_fn(image_url=image_url, image_bytes=image_bytes, options=kwargs)
123
+ else:
124
+ tool_res = await loop.run_in_executor(None, lambda: ds_fn(image_url=image_url, image_bytes=image_bytes, options=kwargs))
125
+ except Exception as e:
126
+ return {"error": f"OCR tool failed: {e}"}
127
+
128
+ doc_id = tool_res.get("doc_id") if isinstance(tool_res, dict) else None
129
+ ocr_text = (tool_res.get("text") if isinstance(tool_res, dict) else str(tool_res)) or ""
130
+
131
+ # Persist OCR text so downstream callers can retrieve it via doc_id
132
+ try:
133
+ if doc_id and ocr_text:
134
+ docs_dir = os.path.join("chat_store", "docs")
135
+ os.makedirs(docs_dir, exist_ok=True)
136
+ doc_path = os.path.join(docs_dir, f"{doc_id}.txt")
137
+ # Write file (overwrite if exists)
138
+ with open(doc_path, "w", encoding="utf-8") as df:
139
+ df.write(ocr_text)
140
+ # Also add a short history entry if agent chat store available
141
+ try:
142
+ if hasattr(aw, 'chat_store_private') and hasattr(aw, 'ChatMessage') and hasattr(aw, 'MessageRole'):
143
+ user_msg = aw.ChatMessage(role=aw.MessageRole.USER, content=f"Uploaded document {doc_id}")
144
+ assistant_msg = aw.ChatMessage(role=aw.MessageRole.ASSISTANT, content=f"OCR stored: {ocr_text[:400]}")
145
+ aw.chat_store_private.add_message(key="conversation", message=user_msg)
146
+ aw.chat_store_private.add_message(key="conversation", message=assistant_msg)
147
+ try:
148
+ aw.chat_store_private.persist(str(aw.private_store_path))
149
+ except Exception:
150
+ pass
151
+ except Exception:
152
+ pass
153
+ except Exception:
154
+ # Non-fatal: continue even if persistence fails
155
+ pass
156
+
157
+ # If a question was provided, answer it using the agent helper (run in executor to avoid blocking)
158
+ if question:
159
+ try:
160
+ # Use executor if helper is sync to avoid blocking event loop
161
+ if callable(getattr(aw, 'ocr_agent_qa', None)):
162
+ answer = await loop.run_in_executor(None, lambda: aw.ocr_agent_qa(question, doc_id))
163
+ return {"doc_id": doc_id, "answer": answer}
164
+ else:
165
+ return {"doc_id": doc_id, "answer": "ocr_agent_qa not available"}
166
+ except Exception as e:
167
+ return {"error": f"ocr_agent_qa failed: {e}", "tool_result": tool_res}
168
+
169
+ # No question: return the OCR result and doc_id
170
+ return {"doc_id": doc_id, "ocr_text": ocr_text}
171
+
172
+ register_tool("ocr_qa", _ocr_qa_tool)
173
+ print(f"[MCP STARTUP] Registered ocr_qa -> real _ocr_qa_tool (agent available)")
174
+ except Exception:
175
+ # If agent import fails, register a tolerant mock tool
176
+ def _ocr_qa_mock(**kwargs):
177
+ return {"doc_id": str(uuid.uuid4()), "answer": "(ocr_qa unavailable - mock response)", "received_args": kwargs}
178
+ register_tool("ocr_qa", _ocr_qa_mock)
179
+ print(f"[MCP STARTUP] Registered ocr_qa -> mock(ocr_qa)")
180
+
181
+ # ------------------------------------------------------------------
182
+ # Deterministic schema-aware SQL helper tools (agentic compliant)
183
+ # ------------------------------------------------------------------
184
+ ENABLE_FAST_SQL = os.environ.get("ENABLE_MCP_FAST_TOOLS", "1") in ("1","true","True")
185
+ if not ENABLE_FAST_SQL:
186
+ print("[MCP STARTUP] Fast SQL tools disabled via ENABLE_MCP_FAST_TOOLS=0")
187
+ return
188
+
189
+ # Initialize database connection if not already done
190
+ if not aw:
191
+ print("[MCP STARTUP][FAST] Agent workflow not available; skipping fast SQL tool registration.")
192
+ return
193
+
194
+ if not getattr(aw, 'inspector', None) or not getattr(aw, 'available_tables', None):
195
+ print("[MCP STARTUP][FAST] Database not initialized; attempting to initialize...")
196
+ try:
197
+ # Initialize database connection - use await since we're in async context.
198
+ # Priority chain mirrors worker startup: 1) env DB 2) active schema
199
+ # profile from the registry 3) bundled demo employee SQLite file.
200
+ db_uri = os.environ.get("DB_CONNECTION_URL")
201
+ if not db_uri:
202
+ demo_db_path = os.path.join(
203
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
204
+ "employee-sample-database", "sqlite", "dataset_small", "employee.db",
205
+ )
206
+ try:
207
+ from .schema_profile import profile_registry as _reg
208
+ _active = _reg.active() or {}
209
+ db_uri = _active.get("db_url")
210
+ except Exception:
211
+ db_uri = None
212
+ if not db_uri and os.path.isfile(demo_db_path):
213
+ db_uri = f"sqlite:///{demo_db_path.replace(os.sep, '/')}"
214
+ print("[MCP STARTUP][FAST] Using bundled demo employee database.")
215
+ if not db_uri:
216
+ print("[MCP STARTUP][FAST] No DB env, active profile, or bundled demo found; skipping fast SQL tool registration.")
217
+ return
218
+ db_result = await aw.initialize_database(db_uri)
219
+ if db_result.get("tables"):
220
+ print(f"[MCP STARTUP][FAST] Database initialized with {len(db_result['tables'])} tables")
221
+ else:
222
+ print("[MCP STARTUP][FAST] Database initialization failed; skipping fast SQL tool registration.")
223
+ return
224
+ except Exception as db_err:
225
+ print(f"[MCP STARTUP][FAST] Database initialization error: {db_err}; skipping fast SQL tool registration.")
226
+ return
227
+
228
+ inspector = aw.inspector
229
+ available_tables = aw.available_tables
230
+
231
+ def _colnames(table: str) -> List[str]:
232
+ try:
233
+ return [c['name'] for c in inspector.get_columns(table_name=table)]
234
+ except Exception:
235
+ return []
236
+
237
+ def _has_tables(*tables: str) -> bool:
238
+ at_lower = {t.lower() for t in available_tables}
239
+ return all(t.lower() in at_lower for t in tables)
240
+
241
+ # Simple validation & sanitization re-use
242
+ validate_sql_query = getattr(aw, 'validate_sql_query', lambda q: {"valid": True})
243
+ fix_common_sql_errors = getattr(aw, 'fix_common_sql_errors', lambda q: q)
244
+
245
+ async def _verify_sql(sql: str, question: str, tag: str) -> str:
246
+ """Optional light LLM verification (short prompt) if LLM available."""
247
+ if not aw or not getattr(aw, 'Settings', None) or not getattr(aw.Settings, 'llm', None):
248
+ return sql
249
+ try:
250
+ _schema_block = ""
251
+ try:
252
+ if aw.ACTIVE_SCHEMA_PROFILE.is_employee_db:
253
+ _schema_block = aw.EMPLOYEE_DB_SCHEMA
254
+ else:
255
+ _schema_block = aw.ACTIVE_SCHEMA_PROFILE.build_digest(max_tables=10)
256
+ except Exception:
257
+ _schema_block = ""
258
+ prompt = (
259
+ (f"{_schema_block}\n\n" if _schema_block else "")
260
+ + "You are an SQL verifier."
261
+ + f" Tag={tag}."
262
+ + " If the candidate SQL is valid and uses only existing tables/columns keep it."
263
+ " If SMALL fixes (alias, LIMIT 100, semicolon) needed, fix them. Never invent tables/columns."
264
+ f"\nQuestion: {question}\nCandidate SQL:\n{sql}\nReturn ONLY final SQL." )
265
+ resp = aw.Settings.llm.complete(prompt=prompt)
266
+ txt = getattr(resp, 'text', str(resp)).strip()
267
+ if '```' in txt:
268
+ parts = re.split(r"```(?:sql)?", txt, flags=re.IGNORECASE)
269
+ txt = '\n'.join(p for p in parts if 'select' in p.lower() or 'with' in p.lower())
270
+ if txt.lower().startswith('sql'):
271
+ txt = txt[3:].strip()
272
+ txt = fix_common_sql_errors(txt)
273
+ v = validate_sql_query(txt)
274
+ if v.get('valid'):
275
+ return txt
276
+ except Exception as ve:
277
+ print(f"[FAST][VERIFY][WARN] Verification failed: {ve}; using original SQL")
278
+ return sql
279
+
280
+ def _build_sql(select_cols: List[str], base_table: str, joins: Optional[List[str]] = None,
281
+ where: Optional[List[str]] = None, group_by: Optional[List[str]] = None,
282
+ order_by: Optional[str] = None, limit: Optional[int] = 100) -> str:
283
+ parts = ["SELECT " + ", ".join(select_cols), "FROM " + base_table]
284
+ for j in (joins or []):
285
+ parts.append(j)
286
+ if where:
287
+ parts.append("WHERE " + " AND ".join(where))
288
+ if group_by:
289
+ parts.append("GROUP BY " + ", ".join(group_by))
290
+ if order_by:
291
+ parts.append("ORDER BY " + order_by)
292
+ if limit is not None:
293
+ parts.append(f"LIMIT {limit}")
294
+ sql = " ".join(parts)
295
+ if not sql.strip().endswith(';'):
296
+ sql += ';'
297
+ return sql
298
+
299
+ async def tool_list_departments(question: str = ""):
300
+ if not _has_tables('department'):
301
+ return {"error": "department table not available"}
302
+ cols = _colnames('department')
303
+ name_col = 'dept_name' if 'dept_name' in cols else (cols[0] if cols else 'dept_name')
304
+ sql = _build_sql([f"d.{name_col} AS department_name"], 'department d', order_by='department_name ASC')
305
+ sql = fix_common_sql_errors(sql)
306
+ sql = await _verify_sql(sql, question or 'List departments', 'list_departments')
307
+ return {"sql": sql}
308
+
309
+ async def tool_count_employees(question: str = ""):
310
+ if not _has_tables('employee'):
311
+ return {"error": "employee table not available"}
312
+ sql = _build_sql(["COUNT(*) AS total_employees"], 'employee e', limit=None)
313
+ sql = fix_common_sql_errors(sql)
314
+ sql = await _verify_sql(sql, question or 'Total employees', 'count_employees')
315
+ return {"sql": sql}
316
+
317
+ async def tool_employee_count_by_department(question: str = ""):
318
+ if not _has_tables('department','dept_emp'):
319
+ return {"error": "required tables missing"}
320
+ dcols = _colnames('department'); decols = _colnames('dept_emp')
321
+ dept_name = 'dept_name' if 'dept_name' in dcols else (dcols[0] if dcols else 'dept_name')
322
+ dept_no = 'dept_no' if 'dept_no' in dcols or 'dept_no' in decols else 'dept_no'
323
+ emp_no = 'emp_no' if 'emp_no' in decols else 'emp_no'
324
+ where = []
325
+ if 'to_date' in decols:
326
+ where.append("de.to_date = '9999-01-01'")
327
+ sql = _build_sql([f"d.{dept_name} AS department_name", f"COUNT(DISTINCT de.{emp_no}) AS employee_count"],
328
+ 'department d', joins=[f"JOIN dept_emp de ON d.{dept_no} = de.{dept_no}"],
329
+ where=where, group_by=[f"d.{dept_name}"], order_by='employee_count DESC')
330
+ sql = fix_common_sql_errors(sql)
331
+ sql = await _verify_sql(sql, question or 'Employees per department', 'employee_count_by_department')
332
+ return {"sql": sql}
333
+
334
+ async def tool_gender_pay_gap(question: str = ""):
335
+ if not _has_tables('department','dept_emp','employee','salary'):
336
+ return {"error": "required tables missing"}
337
+ scolumns = _colnames('salary')
338
+ sval = 'salary' if 'salary' in scolumns else ('amount' if 'amount' in scolumns else (scolumns[0] if scolumns else 'salary'))
339
+ where = ["de.to_date = '9999-01-01'", "s.to_date = '9999-01-01'"]
340
+ sql = _build_sql([
341
+ "d.dept_name",
342
+ f"AVG(CASE WHEN e.gender='M' THEN s.{sval} END) AS avg_male_salary",
343
+ f"AVG(CASE WHEN e.gender='F' THEN s.{sval} END) AS avg_female_salary",
344
+ f"(AVG(CASE WHEN e.gender='M' THEN s.{sval} END) - AVG(CASE WHEN e.gender='F' THEN s.{sval} END)) AS gap",
345
+ f"CASE WHEN AVG(CASE WHEN e.gender='M' THEN s.{sval} END)=0 THEN NULL ELSE ((AVG(CASE WHEN e.gender='M' THEN s.{sval} END) - AVG(CASE WHEN e.gender='F' THEN s.{sval} END))/NULLIF(AVG(CASE WHEN e.gender='M' THEN s.{sval} END),0))*100 END AS pct_gap"
346
+ ], 'department d',
347
+ joins=['JOIN dept_emp de ON d.dept_no = de.dept_no','JOIN employee e ON de.emp_no = e.emp_no','JOIN salary s ON e.emp_no = s.emp_no'],
348
+ where=where, group_by=['d.dept_name'], order_by='gap DESC')
349
+ sql = fix_common_sql_errors(sql)
350
+ sql = await _verify_sql(sql, question or 'Gender pay gap', 'gender_pay_gap')
351
+ return {"sql": sql}
352
+
353
+ async def tool_salary_extremes(question: str = ""):
354
+ if not _has_tables('salary'):
355
+ return {"error": "salary table missing"}
356
+ scolumns = _colnames('salary'); sval = 'salary' if 'salary' in scolumns else ('amount' if 'amount' in scolumns else (scolumns[0] if scolumns else 'salary'))
357
+ where = ["s.to_date = '9999-01-01'"] if 'to_date' in scolumns else []
358
+ sql = _build_sql([f"MAX(s.{sval}) AS highest_salary", f"MIN(s.{sval}) AS lowest_salary"], 'salary s', where=where, limit=None)
359
+ sql = fix_common_sql_errors(sql)
360
+ sql = await _verify_sql(sql, question or 'Salary extremes', 'salary_extremes')
361
+ return {"sql": sql}
362
+
363
+ async def tool_salary_range_department(department_name: str = "Development", question: str = ""):
364
+ if not _has_tables('department','dept_emp','salary'):
365
+ return {"error": "required tables missing"}
366
+ scolumns = _colnames('salary'); sval = 'salary' if 'salary' in scolumns else ('amount' if 'amount' in scolumns else (scolumns[0] if scolumns else 'salary'))
367
+ # Escape single quotes in department_name for SQL safety (basic)
368
+ escaped_dept = department_name.replace("'", "''")
369
+ where = ["de.to_date = '9999-01-01'", "s.to_date = '9999-01-01'", f"d.dept_name = '{escaped_dept}'"]
370
+ sql = _build_sql(["d.dept_name", f"MAX(s.{sval}) AS max_salary", f"MIN(s.{sval}) AS min_salary"], 'department d',
371
+ joins=['JOIN dept_emp de ON d.dept_no = de.dept_no','JOIN salary s ON de.emp_no = s.emp_no'],
372
+ where=where, group_by=['d.dept_name'], limit=None)
373
+ sql = fix_common_sql_errors(sql)
374
+ sql = await _verify_sql(sql, question or 'Department salary range', 'salary_range_department')
375
+ return {"sql": sql, "department": department_name}
376
+
377
+ async def tool_top_paid_employees(top_n: int = 10, question: str = ""):
378
+ if not _has_tables('employee','salary'):
379
+ return {"error": "required tables missing"}
380
+ scolumns = _colnames('salary'); sval = 'salary' if 'salary' in scolumns else (scolumns[0] if scolumns else 'salary')
381
+ where = ["s.to_date = '9999-01-01'"] if 'to_date' in scolumns else []
382
+ sql = _build_sql(["e.emp_no","e.first_name","e.last_name", f"s.{sval} AS salary"], 'employee e',
383
+ joins=['JOIN salary s ON e.emp_no = s.emp_no'], where=where,
384
+ order_by=f"s.{sval} DESC", limit=top_n)
385
+ sql = fix_common_sql_errors(sql)
386
+ sql = await _verify_sql(sql, question or 'Top paid employees', 'top_paid_employees')
387
+ return {"sql": sql, "top_n": top_n}
388
+
389
+ async def tool_department_highest_avg_salary(question: str = ""):
390
+ if not _has_tables('department','dept_emp','salary'):
391
+ return {"error": "required tables missing"}
392
+ scolumns = _colnames('salary'); sval = 'salary' if 'salary' in scolumns else (scolumns[0] if scolumns else 'salary')
393
+ where = ["de.to_date = '9999-01-01'", "s.to_date = '9999-01-01'"]
394
+ sql = _build_sql(["d.dept_name", f"AVG(s.{sval}) AS avg_salary"], 'department d',
395
+ joins=['JOIN dept_emp de ON d.dept_no = de.dept_no','JOIN salary s ON de.emp_no = s.emp_no'],
396
+ where=where, group_by=['d.dept_name'], order_by='avg_salary DESC', limit=1)
397
+ sql = fix_common_sql_errors(sql)
398
+ sql = await _verify_sql(sql, question or 'Department highest average salary', 'dept_highest_avg_salary')
399
+ return {"sql": sql}
400
+
401
+ async def tool_department_manager_listing(question: str = ""):
402
+ if not _has_tables('department','dept_manager','employee'):
403
+ return {"error": "required tables missing"}
404
+ where = ["dm.to_date = '9999-01-01'"]
405
+ sql = _build_sql(["d.dept_name AS department_name","e.first_name","e.last_name"], 'department d',
406
+ joins=['JOIN dept_manager dm ON d.dept_no = dm.dept_no','JOIN employee e ON dm.emp_no = e.emp_no'],
407
+ where=where, order_by='department_name ASC')
408
+ sql = fix_common_sql_errors(sql)
409
+ sql = await _verify_sql(sql, question or 'Department managers', 'department_manager_listing')
410
+ return {"sql": sql}
411
+
412
+ # NEW: Complex analytical tools for business intelligence
413
+ async def tool_gender_distribution_by_dept(question: str = ""):
414
+ if not _has_tables('department','dept_emp','employee'):
415
+ return {"error": "required tables missing"}
416
+ where = ["de.to_date = '9999-01-01'"]
417
+ sql = _build_sql([
418
+ "d.dept_name AS department_name",
419
+ "e.gender",
420
+ "COUNT(*) AS count",
421
+ "ROUND(COUNT(*) * 100.0 / SUM(COUNT(*)) OVER (PARTITION BY d.dept_name), 2) AS percentage"
422
+ ], 'department d',
423
+ joins=['JOIN dept_emp de ON d.dept_no = de.dept_no','JOIN employee e ON de.emp_no = e.emp_no'],
424
+ where=where, group_by=['d.dept_name', 'e.gender'], order_by='department_name, gender')
425
+ sql = fix_common_sql_errors(sql)
426
+ sql = await _verify_sql(sql, question or 'Gender distribution by department', 'gender_distribution_by_dept')
427
+ return {"sql": sql}
428
+
429
+ async def tool_hiring_trend_by_year(question: str = ""):
430
+ if not _has_tables('employee'):
431
+ return {"error": "required table employee missing"}
432
+ sql = _build_sql([
433
+ "EXTRACT(YEAR FROM e.hire_date) AS hire_year",
434
+ "COUNT(*) AS employees_hired",
435
+ "COUNT(CASE WHEN e.gender='M' THEN 1 END) AS male_hires",
436
+ "COUNT(CASE WHEN e.gender='F' THEN 1 END) AS female_hires"
437
+ ], 'employee e', group_by=['EXTRACT(YEAR FROM e.hire_date)'], order_by='hire_year ASC')
438
+ sql = fix_common_sql_errors(sql)
439
+ sql = await _verify_sql(sql, question or 'Hiring trends by year', 'hiring_trend_by_year')
440
+ return {"sql": sql}
441
+
442
+ async def tool_employee_tenure_by_dept(question: str = ""):
443
+ if not _has_tables('department','dept_emp','employee'):
444
+ return {"error": "required tables missing"}
445
+ where = ["de.to_date = '9999-01-01'"]
446
+ sql = _build_sql([
447
+ "d.dept_name AS department_name",
448
+ "AVG(EXTRACT(DAYS FROM (CURRENT_DATE - e.hire_date))/365.25) AS avg_tenure_years",
449
+ "MIN(EXTRACT(DAYS FROM (CURRENT_DATE - e.hire_date))/365.25) AS min_tenure_years",
450
+ "MAX(EXTRACT(DAYS FROM (CURRENT_DATE - e.hire_date))/365.25) AS max_tenure_years"
451
+ ], 'department d',
452
+ joins=['JOIN dept_emp de ON d.dept_no = de.dept_no','JOIN employee e ON de.emp_no = e.emp_no'],
453
+ where=where, group_by=['d.dept_name'], order_by='avg_tenure_years DESC')
454
+ sql = fix_common_sql_errors(sql)
455
+ sql = await _verify_sql(sql, question or 'Employee tenure by department', 'employee_tenure_by_dept')
456
+ return {"sql": sql}
457
+
458
+ async def tool_female_managers_count(question: str = ""):
459
+ if not _has_tables('dept_manager','employee'):
460
+ return {"error": "required tables missing"}
461
+ where = ["dm.to_date = '9999-01-01'", "e.gender = 'F'"]
462
+ sql = _build_sql([
463
+ "COUNT(*) AS female_managers_count",
464
+ "COUNT(*) * 100.0 / (SELECT COUNT(*) FROM dept_manager dm2 WHERE dm2.to_date = '9999-01-01') AS percentage_female_managers"
465
+ ], 'dept_manager dm',
466
+ joins=['JOIN employee e ON dm.emp_no = e.emp_no'],
467
+ where=where, limit=None)
468
+ sql = fix_common_sql_errors(sql)
469
+ sql = await _verify_sql(sql, question or 'Female managers count', 'female_managers_count')
470
+ return {"sql": sql}
471
+
472
+ async def tool_avg_salary_by_title_dept(question: str = ""):
473
+ """Get average salary by title and department."""
474
+ if not _has_tables('department', 'dept_emp', 'salary', 'title', 'employee'):
475
+ return {"error": "required tables missing"}
476
+ where = ["de.to_date = '9999-01-01'", "s.to_date = '9999-01-01'", "t.to_date = '9999-01-01'"]
477
+ sql = _build_sql(["d.dept_name AS department_name", "t.title", "AVG(s.salary) AS avg_salary"], 'department d',
478
+ joins=['JOIN dept_emp de ON d.dept_no = de.dept_no',
479
+ 'JOIN employee e ON de.emp_no = e.emp_no',
480
+ 'JOIN salary s ON e.emp_no = s.emp_no',
481
+ 'JOIN title t ON e.emp_no = t.emp_no'],
482
+ where=where, group_by=['d.dept_name', 't.title'],
483
+ order_by='d.dept_name, avg_salary DESC', limit=100)
484
+ sql = fix_common_sql_errors(sql)
485
+ sql = await _verify_sql(sql, question or 'Average salary by title and department', 'avg_salary_by_title_dept')
486
+ return {"sql": sql}
487
+
488
+ # ---- Registration ----
489
+ # Dynamic schema support: the 14 fast_sql.* tools are purpose-built SQL
490
+ # skeletons for the employee demo schema. Register them only when the
491
+ # active profile IS the employee demo. Otherwise, register the generic
492
+ # schema-grounded tools that work on ANY database.
493
+ is_employee_profile = bool(
494
+ getattr(aw, 'ACTIVE_SCHEMA_PROFILE', None)
495
+ and aw.ACTIVE_SCHEMA_PROFILE.is_employee_db
496
+ )
497
+
498
+ if is_employee_profile:
499
+ register_tool('fast_sql.list_departments', tool_list_departments)
500
+ register_tool('fast_sql.count_employees', tool_count_employees)
501
+ register_tool('fast_sql.employee_count_by_department', tool_employee_count_by_department)
502
+ register_tool('fast_sql.gender_pay_gap', tool_gender_pay_gap) # RE-ENABLED: Complex analytical queries
503
+ register_tool('fast_sql.salary_extremes', tool_salary_extremes)
504
+ register_tool('fast_sql.salary_range_department', tool_salary_range_department)
505
+ register_tool('fast_sql.top_paid_employees', tool_top_paid_employees)
506
+ register_tool('fast_sql.department_highest_avg_salary', tool_department_highest_avg_salary)
507
+ register_tool('fast_sql.department_manager_listing', tool_department_manager_listing)
508
+
509
+ # Register new complex analytical tools
510
+ register_tool('fast_sql.gender_distribution_by_dept', tool_gender_distribution_by_dept)
511
+ register_tool('fast_sql.hiring_trend_by_year', tool_hiring_trend_by_year)
512
+ register_tool('fast_sql.employee_tenure_by_dept', tool_employee_tenure_by_dept)
513
+ register_tool('fast_sql.female_managers_count', tool_female_managers_count)
514
+ register_tool('fast_sql.avg_salary_by_title_dept', tool_avg_salary_by_title_dept)
515
+ print('[MCP STARTUP] Registered employee-demo fast SQL tools: '
516
+ + ', '.join([k for k in TOOLS if k.startswith('fast_sql.')]))
517
+ else:
518
+ # ---------- Generic schema-grounded tools (any database) ----------
519
+ def tool_schema_list_tables(**kwargs):
520
+ return {"tables": list(available_tables)}
521
+
522
+ def tool_schema_describe_table(table: str = "", **kwargs):
523
+ if not table:
524
+ return {"error": "table is required", "tables": list(available_tables)}
525
+ cols = _colnames(table)
526
+ if not cols:
527
+ # Case-insensitive retry
528
+ lower_map = {t.lower(): t for t in available_tables}
529
+ table = lower_map.get(table.lower())
530
+ if table:
531
+ cols = _colnames(table)
532
+ return {"table": table, "exists": bool(cols), "columns": cols}
533
+
534
+ def tool_schema_sample_data(table: str = "", limit: int = 3, **kwargs):
535
+ if not table:
536
+ return {"error": "table is required"}
537
+ try:
538
+ from sqlalchemy import text as _sa_text
539
+ safe_limit = max(1, min(int(limit), 10))
540
+ with aw.sql_database.connect() as conn:
541
+ rows = conn.execute(
542
+ _sa_text(f'SELECT * FROM "{table}" LIMIT {safe_limit}')
543
+ ).mappings().all()
544
+ return {"table": table, "rows": [dict(r) for r in rows]}
545
+ except Exception:
546
+ try:
547
+ from sqlalchemy import text as _sa_text
548
+ safe_limit = max(1, min(int(limit), 10))
549
+ with aw.sql_database.connect() as conn:
550
+ rows = conn.execute(
551
+ _sa_text(f"SELECT * FROM {table} LIMIT {safe_limit}")
552
+ ).mappings().all()
553
+ return {"table": table, "rows": [dict(r) for r in rows]}
554
+ except Exception as e2:
555
+ return {"table": table, "error": str(e2)}
556
+
557
+ async def tool_sql_build_select(select_cols: Optional[List[str]] = None, base_table: str = "",
558
+ joins: Optional[List[str]] = None, where: Optional[List[str]] = None,
559
+ group_by: Optional[List[str]] = None, order_by: Optional[str] = None,
560
+ limit: Optional[int] = 100, question: str = "", **kwargs):
561
+ """Deterministic schema-grounded SELECT builder: validates requested
562
+ columns against the live table, uses SQLAlchemy inspector, then an
563
+ optional light LLM refinement. Returns a validated SQL hint."""
564
+ cols = _colnames(base_table)
565
+ if not cols:
566
+ lower_map = {t.lower(): t for t in available_tables}
567
+ base_table = lower_map.get((base_table or "").lower(), base_table)
568
+ cols = _colnames(base_table)
569
+ if not cols:
570
+ return {"error": f"Unknown table '{base_table}'",
571
+ "tables": list(available_tables)}
572
+ _cols_lower = {str(c).lower(): str(c) for c in cols}
573
+ for raw in (select_cols or []):
574
+ # tokens like alias.col, col, COUNT(col) etc.
575
+ for tok in re.findall(r"[A-Za-z_][\w]*(?:\.[A-Za-z_]\w*)?", str(raw)):
576
+ t_, sep, c_ = tok.partition('.')
577
+ if sep and c_.lower() not in _cols_lower and c_.lower() != '1':
578
+ return {"error": f"Unknown column '{tok}' in table '{base_table}'",
579
+ "columns": cols,
580
+ "hint": "select base_table.column for aggregate args, e.g. COUNT(col)"}
581
+ sql = _build_sql(select_cols=select_cols, base_table=base_table, joins=joins,
582
+ where=where, group_by=group_by, order_by=order_by, limit=limit)
583
+ sql = fix_common_sql_errors(sql)
584
+ sql = await _verify_sql(sql, question or f"SELECT from {base_table}", f"build_select_{base_table}")
585
+ return {"sql": sql, "table": base_table, "columns": cols}
586
+
587
+ register_tool('schema.list_tables', tool_schema_list_tables)
588
+ register_tool('schema.describe_table', tool_schema_describe_table)
589
+ register_tool('schema.sample_data', tool_schema_sample_data)
590
+ register_tool('sql.build_select', tool_sql_build_select)
591
+ print('[MCP STARTUP] Registered GENERIC schema tools: '
592
+ + ', '.join([k for k in TOOLS if k.startswith('schema.') or k.startswith('sql.')]))
593
+ print('[MCP STARTUP] Skipping employee-demo fast_sql.* tools (non-employee schema active)')
594
+
595
+
596
+
597
+ @app.post("/complete")
598
+ async def complete(req: CompleteRequest):
599
+ """Minimal completion endpoint:
600
+ - If context contains {'tool_call': {'name': ..., 'args': {...}}}, the server will run the tool and return its result.
601
+ - Otherwise it returns a simple echo of the prompt under 'text'.
602
+ This scaffold is purposely small so you can extend tool orchestration later.
603
+ """
604
+ ctx = req.context or {}
605
+ # Tool invocation flow
606
+ if 'tool_call' in ctx:
607
+ tc = ctx['tool_call']
608
+ name = tc.get('name')
609
+ args = tc.get('args', {})
610
+ try:
611
+ tool_res = await _call_tool(name, args)
612
+ return {"text": f"Tool '{name}' executed.", "tool_result": tool_res}
613
+ except KeyError as ke:
614
+ raise HTTPException(status_code=404, detail=str(ke))
615
+ except Exception as e:
616
+ raise HTTPException(status_code=500, detail=f"Tool call failed: {e}")
617
+
618
+ # No tool requested: return a simple completion echo for now
619
+ # Future: integrate a local model here and tool loop orchestration
620
+ return {"text": req.prompt}
621
+
622
+
623
+ @app.get("/tools")
624
+ def list_tools():
625
+ return {"tools": list(TOOLS.keys())}
626
+
627
+
628
+ @app.get("/health")
629
+ def health():
630
+ return {"status": "ok", "tools_registered": len(TOOLS)}
Agent/memory_manager.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Memory management utilities for the text2sql agent.
3
+ """
4
+ import gc
5
+ import os
6
+ import time
7
+ import psutil
8
+ import threading
9
+ import weakref
10
+ from contextlib import contextmanager
11
+ from typing import Optional, Callable, Dict, Any
12
+
13
+ class MemoryManager:
14
+ """Memory manager for monitoring and managing system memory."""
15
+
16
+ def __init__(self, threshold_mb: float = 1000.0, critical_mb: float = 300.0,
17
+ check_interval: float = 0.5, monitor_active: bool = True):
18
+ """Initialize the memory manager.
19
+
20
+ Args:
21
+ threshold_mb: Memory threshold in MB below which to take action
22
+ critical_mb: Critical memory level in MB below which to abort operations
23
+ check_interval: Interval in seconds for background memory checks
24
+ monitor_active: Whether to start the background monitor thread
25
+ """
26
+ # Allow environment overrides to tune aggressiveness
27
+ try:
28
+ _env_threshold = os.environ.get("MEM_THRESHOLD_MB")
29
+ _env_critical = os.environ.get("MEM_CRITICAL_MB")
30
+ if _env_threshold: threshold_mb = float(_env_threshold)
31
+ if _env_critical: critical_mb = float(_env_critical)
32
+ except Exception:
33
+ pass
34
+ self.threshold_mb = threshold_mb
35
+ self.critical_mb = critical_mb
36
+ self.check_interval = check_interval
37
+ self._lock = threading.RLock()
38
+ self._monitor_thread = None
39
+ self._keep_monitoring = False
40
+
41
+ # Track instances with weak references when possible to avoid holding
42
+ # strong references that prevent GC. Keep a fallback list for objects
43
+ # that are not weak-referenceable.
44
+ self._active_llm_refs = [] # list of weakref.ref where possible
45
+ self._active_llm_strong = [] # fallback strong refs
46
+ self._instance_count = 0
47
+
48
+ # Soft cap to avoid accidentally registering many parallel LLMs
49
+ self.max_instances = 1
50
+
51
+ # Margin (MB) above critical required to allow new registrations
52
+ self.registration_margin_mb = 200.0
53
+
54
+ # Track last emergency cleanup time to avoid repeated rapid-fire releases
55
+ self._last_emergency = 0.0
56
+ self._emergency_cooldown = 10.0 # seconds between emergency attempts
57
+ # Counter-based suspension flag to prevent emergency releases while in critical sections
58
+ self._suspend_emergency_depth = 0
59
+
60
+ # Minimum available memory (MB) at which we will STILL retain a single LLM instance
61
+ # even if below critical, to avoid thrashing (re-init cost is high). Configurable.
62
+ try:
63
+ self.min_retain_mb = float(os.environ.get("MIN_RETAIN_LLM_MB", "250"))
64
+ except Exception:
65
+ self.min_retain_mb = 250.0
66
+
67
+ # Start memory monitor if requested
68
+ if monitor_active:
69
+ self.start_monitor()
70
+
71
+ def _prune_active_instances(self):
72
+ """Remove dead weakrefs and return list of live instances."""
73
+ live = []
74
+ # Prune weak refs
75
+ for ref in list(self._active_llm_refs):
76
+ inst = ref()
77
+ if inst is None:
78
+ try:
79
+ self._active_llm_refs.remove(ref)
80
+ except ValueError:
81
+ pass
82
+ else:
83
+ live.append(inst)
84
+ # Add strong refs
85
+ for inst in list(self._active_llm_strong):
86
+ if inst is not None:
87
+ live.append(inst)
88
+ return live
89
+
90
+ def register_llm_instance(self, llm_instance):
91
+ """Register an LLM instance for tracking.
92
+
93
+ This will refuse registration (and attempt to release the provided
94
+ instance) if the system memory is too low. It prefers weak references
95
+ so that the manager itself does not keep objects alive.
96
+ """
97
+ with self._lock:
98
+ # Prune dead weakrefs first
99
+ self._prune_active_instances()
100
+
101
+ stats = self.get_memory_stats()
102
+ # Relax policy: always allow the FIRST instance as long as we are above critical.
103
+ # Only enforce margin for additional instances (even though max_instances is 1 today).
104
+ if self._instance_count == 0:
105
+ if stats['available_mb'] < self.critical_mb:
106
+ # Too dangerous even for first instance
107
+ try:
108
+ if hasattr(llm_instance, 'close'):
109
+ llm_instance.close()
110
+ elif hasattr(llm_instance, 'release'):
111
+ llm_instance.release()
112
+ except Exception:
113
+ pass
114
+ raise MemoryError(f"Refusing first LLM registration: below critical ({stats['available_mb']:.1f}MB < {self.critical_mb}MB)")
115
+ else:
116
+ # For subsequent instances keep the stricter margin
117
+ if stats['available_mb'] < (self.critical_mb + self.registration_margin_mb):
118
+ try:
119
+ if hasattr(llm_instance, 'close'):
120
+ llm_instance.close()
121
+ elif hasattr(llm_instance, 'release'):
122
+ llm_instance.release()
123
+ except Exception:
124
+ pass
125
+ raise MemoryError(f"Refusing to register additional LLM (avail={stats['available_mb']:.1f}MB; need >= {self.critical_mb + self.registration_margin_mb:.1f}MB)")
126
+
127
+ # Enforce max instances cap
128
+ if self._instance_count >= self.max_instances:
129
+ raise MemoryError(f"Refusing to register LLM instance: max_instances={self.max_instances} reached")
130
+
131
+ # Try to create a weakref to avoid holding a strong reference
132
+ try:
133
+ ref = weakref.ref(llm_instance, lambda r: None)
134
+ self._active_llm_refs.append(ref)
135
+ except TypeError:
136
+ # Object not weak-referenceable; store strong ref but warn
137
+ self._active_llm_strong.append(llm_instance)
138
+
139
+ self._instance_count += 1
140
+ print(f"LLM instance registered (total: {self._instance_count})")
141
+
142
+ def unregister_llm_instance(self, llm_instance):
143
+ """Unregister an LLM instance from tracking."""
144
+ with self._lock:
145
+ # Remove from weak refs
146
+ removed = False
147
+ for ref in list(self._active_llm_refs):
148
+ inst = ref()
149
+ if inst is None:
150
+ # Dead ref; prune
151
+ try:
152
+ self._active_llm_refs.remove(ref)
153
+ except ValueError:
154
+ pass
155
+ continue
156
+ if inst is llm_instance:
157
+ try:
158
+ self._active_llm_refs.remove(ref)
159
+ except ValueError:
160
+ pass
161
+ removed = True
162
+ break
163
+
164
+ # Remove from strong refs
165
+ if not removed:
166
+ for i, instance in enumerate(list(self._active_llm_strong)):
167
+ if instance is llm_instance:
168
+ del self._active_llm_strong[i]
169
+ removed = True
170
+ break
171
+
172
+ if removed:
173
+ self._instance_count = max(0, self._instance_count - 1)
174
+ print(f"LLM instance unregistered (remaining: {self._instance_count})")
175
+
176
+ def get_memory_stats(self) -> Dict[str, float]:
177
+ """Get current memory statistics."""
178
+ vm = psutil.virtual_memory()
179
+ return {
180
+ "total_mb": vm.total / (1024 * 1024),
181
+ "available_mb": vm.available / (1024 * 1024),
182
+ "used_mb": vm.used / (1024 * 1024),
183
+ "percent_used": vm.percent
184
+ }
185
+
186
+ def is_memory_safe(self) -> bool:
187
+ """Check if memory is at a safe level."""
188
+ return self.get_memory_stats()["available_mb"] >= self.threshold_mb
189
+
190
+ def is_memory_critical(self) -> bool:
191
+ """Check if memory is at a critical level."""
192
+ stats = self.get_memory_stats()
193
+ available = stats["available_mb"]
194
+ is_critical = available <= self.critical_mb
195
+
196
+ # Debug logging for memory state
197
+ if is_critical:
198
+ print(f"🚨 [MEMORY_DEBUG] Critical state: {available:.1f}MB <= {self.critical_mb}MB threshold")
199
+
200
+ return is_critical
201
+
202
+ def force_collect_garbage(self):
203
+ """Force aggressive garbage collection."""
204
+ # Run multiple collection cycles
205
+ for i in range(3):
206
+ gc.collect(i)
207
+
208
+ # Clear any reference cycles
209
+ if hasattr(gc, 'freeze'):
210
+ gc.freeze()
211
+
212
+ # Clear module caches if possible
213
+ if hasattr(gc, 'clear_caches'):
214
+ gc.clear_caches()
215
+
216
+ # Log memory status after cleanup
217
+ stats = self.get_memory_stats()
218
+ #print(f"After garbage collection: {stats['available_mb']:.2f}MB available ({stats['percent_used']}% used)")
219
+
220
+ def _monitor_memory(self):
221
+ """Background thread for memory monitoring."""
222
+ while self._keep_monitoring:
223
+ stats = self.get_memory_stats()
224
+
225
+ # Check for critical memory conditions
226
+ if stats["available_mb"] <= self.critical_mb:
227
+ #print(f"⚠️ CRITICAL MEMORY WARNING: Only {stats['available_mb']:.2f}MB available!")
228
+ self.force_collect_garbage()
229
+
230
+ # If still critical after cleanup, take more drastic measures
231
+ if self.is_memory_critical():
232
+ now = time.time()
233
+ # Only attempt emergency release if cooldown passed
234
+ if now - self._last_emergency > self._emergency_cooldown:
235
+ # Check if we have tracked instances (prune dead refs first)
236
+ live = self._prune_active_instances()
237
+ if live:
238
+ # If only a single LLM instance and we still have above min_retain_mb, skip releasing to prevent constant re-init.
239
+ if len(live) == 1 and stats["available_mb"] > self.min_retain_mb:
240
+ print(f"⚠️ Critical memory but retaining single LLM (avail={stats['available_mb']:.1f}MB > {self.min_retain_mb}MB safeguard)")
241
+ else:
242
+ # Skip emergency release while suspended
243
+ if self._suspend_emergency_depth > 0:
244
+ print(f"🚫 Emergency release suppressed (depth={self._suspend_emergency_depth}) during critical section")
245
+ else:
246
+ self._emergency_release_llm_instances()
247
+ else:
248
+ # Log once per cooldown when no instances are registered
249
+ print("🚨 Emergency memory state detected but no LLM instances registered to release")
250
+ self._last_emergency = now
251
+ else:
252
+ # Cooldown active; skip repeated emergency attempts
253
+ pass
254
+
255
+ # Regular check for low memory
256
+ elif stats["available_mb"] <= self.threshold_mb:
257
+ #print(f"⚠️ Low memory warning: {stats['available_mb']:.2f}MB available")
258
+ self.force_collect_garbage()
259
+
260
+ # Sleep for the check interval
261
+ time.sleep(self.check_interval)
262
+
263
+ def _emergency_release_llm_instances(self):
264
+ """Emergency release of LLM instances to free memory."""
265
+ with self._lock:
266
+ # Build list of live instances from weak and strong refs
267
+ instances = self._prune_active_instances()
268
+ print(f"Attempting to release {len(instances)} LLM instances")
269
+
270
+ for llm in instances:
271
+ try:
272
+ # Try to close or release resources
273
+ if hasattr(llm, 'close'):
274
+ llm.close()
275
+ elif hasattr(llm, 'release'):
276
+ llm.release()
277
+
278
+ # Set to None to break references
279
+ if hasattr(llm, '_client'):
280
+ llm._client = None
281
+ if hasattr(llm, '_model'):
282
+ llm._model = None
283
+ except Exception as e:
284
+ print(f"Error releasing LLM instance: {str(e)}")
285
+
286
+ # Clear our tracking lists
287
+ self._active_llm_refs.clear()
288
+ self._active_llm_strong.clear()
289
+ self._instance_count = 0
290
+
291
+ # Force garbage collection after cleanup and attempt to return pages
292
+ self.force_collect_garbage()
293
+ try:
294
+ # Best-effort working set trim to return pages to OS (Windows)
295
+ self.trim_working_set()
296
+ except Exception:
297
+ pass
298
+
299
+ # ---------------- Public high-level cleanup APIs -----------------
300
+ def release_all_llms(self):
301
+ """Public wrapper to release all tracked LLM instances (non-emergency manual call)."""
302
+ self._emergency_release_llm_instances()
303
+
304
+ def trim_working_set(self):
305
+ """Attempt to return unused pages to OS (best-effort, platform-specific)."""
306
+ try:
307
+ import platform, ctypes
308
+ if platform.system().lower() == 'windows':
309
+ PROCESS_SET_QUOTA = 0x0100
310
+ PROCESS_QUERY_INFORMATION = 0x0400
311
+ kernel32 = ctypes.windll.kernel32
312
+ psapi = ctypes.windll.psapi
313
+ GetCurrentProcess = kernel32.GetCurrentProcess
314
+ hProc = GetCurrentProcess()
315
+ psapi.EmptyWorkingSet(hProc)
316
+ else:
317
+ # For *nix, reading /proc/self might encourage trimming after gc
318
+ pass
319
+ except Exception as e:
320
+ print(f"Working set trim not supported/failed: {e}")
321
+
322
+ def perform_full_cleanup(self) -> Dict[str, float]:
323
+ """Comprehensive cleanup: release LLMs, GC, trim working set, return new stats."""
324
+ before = self.get_memory_stats()
325
+ self.release_all_llms()
326
+ self.force_collect_garbage()
327
+ self.trim_working_set()
328
+ after = self.get_memory_stats()
329
+ delta = after['available_mb'] - before['available_mb']
330
+ print(f"Post-query full cleanup reclaimed {delta:.2f}MB (avail: {after['available_mb']:.2f}MB)")
331
+ return after
332
+
333
+ # --------------- Critical section helpers ---------------
334
+ @contextmanager
335
+ def suspend_emergency(self, reason: str = ""):
336
+ """Context manager to temporarily suspend emergency LLM releases.
337
+
338
+ Use around critical sections (e.g., active LLM generation) to prevent
339
+ the monitor thread from tearing down the only LLM mid-call, which can
340
+ cause intermittent generation failures.
341
+ """
342
+ with self._lock:
343
+ self._suspend_emergency_depth += 1
344
+ if reason:
345
+ print(f"⏸️ Suspended emergency releases (depth={self._suspend_emergency_depth}) reason={reason}")
346
+ try:
347
+ yield
348
+ finally:
349
+ with self._lock:
350
+ self._suspend_emergency_depth = max(0, self._suspend_emergency_depth - 1)
351
+ if reason:
352
+ print(f"▶️ Resumed emergency releases (depth={self._suspend_emergency_depth}) reason={reason}")
353
+
354
+ def start_monitor(self):
355
+ """Start the background memory monitor."""
356
+ with self._lock:
357
+ if self._monitor_thread is None or not self._monitor_thread.is_alive():
358
+ self._keep_monitoring = True
359
+ self._monitor_thread = threading.Thread(
360
+ target=self._monitor_memory,
361
+ daemon=True,
362
+ name="MemoryMonitorThread"
363
+ )
364
+ self._monitor_thread.start()
365
+ print("Memory monitor started in background")
366
+
367
+ def stop_monitor(self):
368
+ """Stop the background memory monitor."""
369
+ with self._lock:
370
+ self._keep_monitoring = False
371
+ if self._monitor_thread and self._monitor_thread.is_alive():
372
+ self._monitor_thread.join(timeout=1.0)
373
+ print("Memory monitor stopped")
374
+
375
+ # Create a global memory manager instance
376
+ memory_manager = MemoryManager(
377
+ threshold_mb=500.0, # 500MB — warning/action threshold (reduced from 1000MB)
378
+ critical_mb=300.0, # 300MB — BSOD-protection hard floor (unchanged)
379
+ check_interval=1.0, # Check every second
380
+ monitor_active=True # Start monitoring immediately
381
+ )
382
+
383
+ class TimeoutManager:
384
+ """Manages operation timeouts with proper cleanup."""
385
+
386
+ @staticmethod
387
+ def run_with_timeout(func: Callable, timeout: float, *args, **kwargs) -> Any:
388
+ """
389
+ Run a function with a timeout.
390
+
391
+ Args:
392
+ func: Function to run
393
+ timeout: Timeout in seconds
394
+ *args, **kwargs: Arguments to pass to the function
395
+
396
+ Returns:
397
+ The result of the function
398
+
399
+ Raises:
400
+ TimeoutError: If the function times out
401
+ """
402
+ result = None
403
+ exception = None
404
+ completed = threading.Event()
405
+
406
+ # Thread function
407
+ def worker():
408
+ nonlocal result, exception
409
+ try:
410
+ result = func(*args, **kwargs)
411
+ except Exception as e:
412
+ exception = e
413
+ finally:
414
+ completed.set()
415
+
416
+ # Start the worker thread
417
+ thread = threading.Thread(target=worker, daemon=True)
418
+ thread.start()
419
+
420
+ # Wait for completion or timeout
421
+ if not completed.wait(timeout):
422
+ # Force garbage collection before raising timeout
423
+ memory_manager.force_collect_garbage()
424
+
425
+ # Raise timeout error
426
+ raise TimeoutError(f"Operation timed out after {timeout} seconds")
427
+
428
+ # If there was an exception, raise it
429
+ if exception is not None:
430
+ raise exception
431
+
432
+ return result
433
+
434
+ def safe_check_memory(threshold_mb: Optional[float] = None) -> bool:
435
+ """
436
+ Safely check if there's enough memory available.
437
+ Also performs garbage collection if memory is low.
438
+
439
+ Args:
440
+ threshold_mb: Optional threshold in MB (uses memory manager's threshold if None)
441
+
442
+ Returns:
443
+ True if memory is safe, False if it's below threshold
444
+ """
445
+ # Use memory manager's threshold if none provided
446
+ if threshold_mb is None:
447
+ threshold_mb = memory_manager.threshold_mb
448
+
449
+ # Get current memory stats
450
+ stats = memory_manager.get_memory_stats()
451
+
452
+ # Log memory status
453
+ print(f"Memory status: {stats['available_mb']:.2f}MB available of {stats['total_mb']:.2f}MB total")
454
+
455
+ # If memory is below threshold, run garbage collection
456
+ if stats['available_mb'] < threshold_mb:
457
+ memory_manager.force_collect_garbage()
458
+
459
+ # Get updated stats after garbage collection
460
+ stats = memory_manager.get_memory_stats()
461
+
462
+ # If still below threshold, return False
463
+ if stats['available_mb'] < threshold_mb:
464
+ print(f"⚠️ Low memory warning: Only {stats['available_mb']:.2f}MB available, need at least {threshold_mb:.2f}MB")
465
+ return False
466
+
467
+ return True
Agent/merge_lora_to_ollama.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Merge a PEFT LoRA adapter (Gemma 1B) into base weights and prepare an Ollama model directory.
2
+
3
+ Usage (after installing extra deps in requirements.txt):
4
+ python Agent/merge_lora_to_ollama.py \
5
+ --base google/gemma-1.1-1b-it \
6
+ --adapter-dir Agent/Gemma3_1B_weights \
7
+ --out-dir merged_gemma1b_text2sql \
8
+ --ollama-model-name gemma1b-text2sql
9
+
10
+ Then create the Ollama model:
11
+ (In PowerShell)
12
+ ollama create gemma1b-text2sql -f merged_gemma1b_text2sql/Modelfile
13
+
14
+ Finally set FINETUNED_MODEL_NAME=gemma1b-text2sql in your .env (or environment) and run the agent.
15
+
16
+ Notes:
17
+ - Ensure you used the SAME base checkpoint for finetuning as you pass via --base.
18
+ - Script keeps everything on CPU (device_map="cpu") to stay RAM friendly; you can add --load-in-8bit if you install bitsandbytes and have GPU.
19
+ """
20
+ import argparse
21
+ import json
22
+ import os
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ from huggingface_hub import HfApi
27
+ try: # Compatibility across hub versions
28
+ from huggingface_hub.errors import RepositoryNotFoundError # type: ignore
29
+ except Exception: # Older versions
30
+ class RepositoryNotFoundError(Exception):
31
+ pass
32
+
33
+ import torch
34
+ from transformers import AutoModelForCausalLM, AutoTokenizer
35
+ from peft import PeftModel
36
+
37
+
38
+ def _detect_base_from_adapter(adapter_dir: str) -> str | None:
39
+ p = Path(adapter_dir)
40
+ resolved = p.resolve()
41
+ print(f"[auto-base] Inspecting adapter_dir: {adapter_dir} -> {resolved}")
42
+ if not resolved.exists():
43
+ print(f"[auto-base] Directory does not exist: {resolved}")
44
+ # Attempt smart fallbacks (common when user runs inside Agent/ already)
45
+ candidates = []
46
+ name = p.name
47
+ cwd = Path.cwd()
48
+ candidates.append(cwd / name)
49
+ candidates.append(cwd.parent / name)
50
+ candidates.append(cwd.parent / 'Agent' / name)
51
+ for cand in candidates:
52
+ if cand.exists():
53
+ print(f"[auto-base] Found alternative adapter dir: {cand}")
54
+ resolved = cand
55
+ break
56
+ if not resolved.exists():
57
+ print(f"[auto-base] Fallback search failed. Tried: {[str(c) for c in candidates]}")
58
+ return None
59
+ cfg_path = resolved / "adapter_config.json"
60
+ if not cfg_path.exists():
61
+ try:
62
+ contents = [c.name for c in resolved.iterdir()]
63
+ except Exception:
64
+ contents = []
65
+ print(f"[auto-base] adapter_config.json not found in {resolved}. Contents: {contents}")
66
+ return None
67
+ try:
68
+ raw = cfg_path.read_text(encoding="utf-8")
69
+ print(f"[auto-base] Found adapter_config.json ({len(raw)} bytes)")
70
+ data = json.loads(raw)
71
+ base = data.get("base_model_name_or_path")
72
+ print(f"[auto-base] base_model_name_or_path: {base}")
73
+ return base
74
+ except Exception as e:
75
+ print(f"[auto-base] Failed reading adapter_config.json: {e}")
76
+ return None
77
+
78
+
79
+ def merge_adapter(base: str, adapter_dir: str, out_dir: str, ollama_model_name: str, template_temperature: float = 0.05, hf_token: str | None = None, local_files_only: bool = False, auto_base: bool = False, trust_remote_code: bool = True):
80
+ out_path = Path(out_dir)
81
+ out_path.mkdir(parents=True, exist_ok=True)
82
+
83
+ if auto_base or base.lower() == "auto":
84
+ detected = _detect_base_from_adapter(adapter_dir)
85
+ if detected:
86
+ print(f"[auto-base] Detected base model from adapter_config: {detected}")
87
+ base = detected
88
+ else:
89
+ raise RuntimeError("Could not auto-detect base model; supply --base explicitly.")
90
+
91
+ auth_kwargs = {}
92
+ if hf_token:
93
+ # Only pass 'token' (use_auth_token deprecated & causes conflict if both set)
94
+ auth_kwargs = {"token": hf_token}
95
+ os.environ.setdefault("HF_TOKEN", hf_token)
96
+ os.environ.setdefault("HUGGINGFACEHUB_API_TOKEN", hf_token)
97
+ print(f"Using HF token (masked): {hf_token[:8]}... (length {len(hf_token)})")
98
+
99
+ # Quick repo existence check (skipped if local_files_only)
100
+ if not local_files_only:
101
+ try:
102
+ HfApi().model_info(base, token=hf_token)
103
+ except RepositoryNotFoundError:
104
+ print(f"\n[ERROR] Base model repo '{base}' not found on Hugging Face.\n")
105
+ print("Troubleshooting:")
106
+ print(" - Verify the exact model id: e.g. 'google/gemma-2-2b-it' or 'google/gemma-1.1-2b-it'.")
107
+ print(" - If it's a gated/private model ensure your token has accepted the terms.")
108
+ print(" - Pass --hf-token YOUR_TOKEN or set HF_TOKEN env var.")
109
+ return 2
110
+ except Exception as e:
111
+ print(f"[WARN] Could not verify model existence pre-download: {e}")
112
+
113
+ print(f"Loading base model: {base} (local_files_only={local_files_only})")
114
+ try:
115
+ tokenizer = AutoTokenizer.from_pretrained(base, local_files_only=local_files_only, **auth_kwargs)
116
+ except Exception as e:
117
+ msg = str(e)
118
+ if "403" in msg or "Forbidden" in msg:
119
+ print("\n[AUTH ERROR] 403 while fetching tokenizer/config.")
120
+ print("Checklist:")
121
+ print(" 1. Ensure token has: 'Read access to public gated models'.")
122
+ print(" 2. Visit model page and accept license (if not already).")
123
+ print(" 3. If using a fine-grained token, enable 'Gated repos' permission.")
124
+ print(" 4. Retry with: --hf-token $env:HF_TOKEN (PowerShell: $env:HF_TOKEN='xxxx')")
125
+ print(" 5. If model already cached on another machine, copy that ~/.cache/huggingface/hub directory.")
126
+ raise
127
+
128
+ # Keep on CPU to reduce VRAM needs; if you want faster and have GPU, remove device_map and add torch_dtype.
129
+ model_kwargs = dict(
130
+ device_map="cpu",
131
+ local_files_only=local_files_only,
132
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
133
+ **auth_kwargs,
134
+ )
135
+ if trust_remote_code:
136
+ model_kwargs["trust_remote_code"] = True
137
+ # Lower RAM peak during load
138
+ model_kwargs["low_cpu_mem_usage"] = True
139
+
140
+ try:
141
+ print("[stage] Downloading / loading base model weights...")
142
+ base_model = AutoModelForCausalLM.from_pretrained(base, **model_kwargs)
143
+ print("[stage] Base model loaded successfully.")
144
+ except ValueError as ve:
145
+ msg = str(ve)
146
+ if "does not recognize this architecture" in msg or "model type" in msg:
147
+ print("[model-load] Unrecognized model type. Attempting retry after upgrading transformers may be required.")
148
+ print("Suggestion: pip install --upgrade transformers huggingface_hub --no-cache-dir")
149
+ if not trust_remote_code:
150
+ print("Retrying with trust_remote_code=True ...")
151
+ model_kwargs["trust_remote_code"] = True
152
+ base_model = AutoModelForCausalLM.from_pretrained(base, **model_kwargs)
153
+ else:
154
+ # Last resort: advise source install
155
+ raise
156
+ else:
157
+ raise
158
+ except Exception as e:
159
+ msg = str(e)
160
+ if "403" in msg or "Forbidden" in msg:
161
+ print("\n[AUTH ERROR] 403 while fetching model weights (config or pytorch model). See guidance above.")
162
+ raise
163
+
164
+ print(f"Loading LoRA adapter from: {adapter_dir}")
165
+ peft_model = PeftModel.from_pretrained(base_model, adapter_dir)
166
+ print("[stage] LoRA adapter loaded.")
167
+
168
+ print("Merging LoRA weights into base weights (this may take a minute)...")
169
+ merged_model = peft_model.merge_and_unload()
170
+ print("[stage] Merge complete in-memory.")
171
+
172
+ print(f"Saving merged model to: {out_dir}")
173
+ merged_model.save_pretrained(out_dir)
174
+ tokenizer.save_pretrained(out_dir)
175
+ print("[stage] Saved model and tokenizer.")
176
+
177
+ # Create a simple Modelfile for Ollama (avoid nested triple-quote confusion)
178
+ modelfile_lines = [
179
+ # Use current directory as model context so Modelfile works regardless of parent path
180
+ "FROM .",
181
+ f"PARAMETER temperature {template_temperature}",
182
+ "# Basic template; adjust if you have a custom chat format.",
183
+ 'TEMPLATE """{{ .Prompt }}"""',
184
+ ""
185
+ ]
186
+ modelfile = "\n".join(modelfile_lines)
187
+ (out_path / "Modelfile").write_text(modelfile, encoding="utf-8")
188
+
189
+ meta = {
190
+ "base": base,
191
+ "adapter_dir": adapter_dir,
192
+ "merged_dir": out_dir,
193
+ "ollama_model_name": ollama_model_name,
194
+ "temperature": template_temperature,
195
+ }
196
+ (out_path / "merge_metadata.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
197
+
198
+ print("Merge complete. Next steps:")
199
+ print(f" 1. ollama create {ollama_model_name} -f {out_dir}/Modelfile")
200
+ print(f" 2. Set FINETUNED_MODEL_NAME={ollama_model_name}")
201
+ print(" 3. Run your agent code again.")
202
+
203
+
204
+ def main():
205
+ if len(sys.argv) == 1:
206
+ print("\n[merge_lora_to_ollama] Missing arguments. Example usage:\n")
207
+ print("python Agent/merge_lora_to_ollama.py \\")
208
+ print(" --base google/gemma-1.1-1b-it \\")
209
+ print(" --adapter-dir Agent/Gemma3_1B_weights \\")
210
+ print(" --out-dir merged_gemma1b_text2sql \\")
211
+ print(" --ollama-model-name gemma1b-text2sql\n")
212
+ return 1
213
+
214
+ parser = argparse.ArgumentParser(description="Merge a Gemma LoRA adapter for Ollama usage.")
215
+ parser.add_argument("--base", required=True, help="Base HF model id used during finetuning (e.g., google/gemma-3-1b-it or 'auto' to read adapter_config)")
216
+ parser.add_argument("--auto-base", action="store_true", help="Ignore --base value and read base from adapter_config.json")
217
+ parser.add_argument("--adapter-dir", required=True, help="Path to the LoRA adapter directory (with adapter_model.safetensors)")
218
+ parser.add_argument("--out-dir", required=True, help="Directory to write merged weights and Modelfile")
219
+ parser.add_argument("--ollama-model-name", required=True, help="Target Ollama model name to create")
220
+ parser.add_argument("--temperature", type=float, default=0.05, help="Default temperature for Modelfile")
221
+ parser.add_argument("--hf-token", help="Hugging Face access token (optional; else read HF_TOKEN / HUGGINGFACEHUB_API_TOKEN env)")
222
+ parser.add_argument("--local-files-only", action="store_true", help="Do not attempt to download; require weights to be cached locally")
223
+ parser.add_argument("--no-trust-remote-code", action="store_true", help="Disable trust_remote_code (not recommended for Gemma 3)")
224
+ args = parser.parse_args()
225
+
226
+ hf_token = args.hf_token or os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
227
+ if not hf_token:
228
+ print("[INFO] No HF token provided. If the model is gated/private, pass --hf-token or set HF_TOKEN env.")
229
+
230
+ merge_adapter(
231
+ base=args.base,
232
+ adapter_dir=args.adapter_dir,
233
+ out_dir=args.out_dir,
234
+ ollama_model_name=args.ollama_model_name,
235
+ template_temperature=args.temperature,
236
+ hf_token=hf_token,
237
+ local_files_only=args.local_files_only,
238
+ auto_base=args.auto_base,
239
+ trust_remote_code=not args.no_trust_remote_code,
240
+ )
241
+
242
+
243
+ if __name__ == "__main__":
244
+ main()
Agent/merge_qwen_to_ollama.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """Merge a PEFT LoRA adapter (Qwen 2.5 3b) into base weights and prepare an Ollama model directory.
3
+
4
+ This is a standalone, non-destructive helper. It follows the same pattern as
5
+ `Agent/merge_lora_to_ollama.py` but defaults to a Qwen base and includes flags
6
+ for optional low-memory / 8-bit loading.
7
+
8
+ Usage (PowerShell):
9
+ Agent/merge_qwen_to_ollama.py \
10
+ --base Qwenpython/Qwen2.5-3B-Instruct \
11
+ --adapter-dir Agent/Qwen2.5_3b_weights \
12
+ --out-dir merged_qwen2_5_3b_text2sql \
13
+ --ollama-model-name qwen2.5-text2sql
14
+
15
+ Notes:
16
+ - Keeps merge on CPU to minimize peak memory.
17
+ - If you have a GPU and want faster tokenizers/model ops, see OLLAMA GPU notes file.
18
+ """
19
+ import argparse
20
+ import json
21
+ import os
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ try:
26
+ from huggingface_hub import HfApi
27
+ except Exception:
28
+ HfApi = None
29
+
30
+ import torch
31
+ from transformers import AutoModelForCausalLM, AutoTokenizer
32
+ from peft import PeftModel
33
+ from transformers import BitsAndBytesConfig
34
+
35
+ def _detect_base_from_adapter(adapter_dir: str) -> str | None:
36
+ p = Path(adapter_dir)
37
+ resolved = p.resolve()
38
+ print(f"[auto-base] Inspecting adapter_dir: {adapter_dir} -> {resolved}")
39
+ if not resolved.exists():
40
+ print(f"[auto-base] Directory does not exist: {resolved}")
41
+ # Attempt smart fallbacks (common when user runs inside Agent/ already)
42
+ candidates = []
43
+ name = p.name
44
+ cwd = Path.cwd()
45
+ candidates.append(cwd / name)
46
+ candidates.append(cwd.parent / name)
47
+ candidates.append(cwd.parent / 'Agent' / name)
48
+ for cand in candidates:
49
+ if cand.exists():
50
+ print(f"[auto-base] Found alternative adapter dir: {cand}")
51
+ resolved = cand
52
+ break
53
+ if not resolved.exists():
54
+ print(f"[auto-base] Fallback search failed. Tried: {[str(c) for c in candidates]}")
55
+ return None
56
+ cfg_path = resolved / "adapter_config.json"
57
+ if not cfg_path.exists():
58
+ try:
59
+ contents = [c.name for c in resolved.iterdir()]
60
+ except Exception:
61
+ contents = []
62
+ print(f"[auto-base] adapter_config.json not found in {resolved}. Contents: {contents}")
63
+ return None
64
+ try:
65
+ raw = cfg_path.read_text(encoding="utf-8")
66
+ print(f"[auto-base] Found adapter_config.json ({len(raw)} bytes)")
67
+ data = json.loads(raw)
68
+ base = data.get("base_model_name_or_path")
69
+ print(f"[auto-base] base_model_name_or_path: {base}")
70
+ return base
71
+ except Exception as e:
72
+ print(f"[auto-base] Failed reading adapter_config.json: {e}")
73
+ return None
74
+
75
+ def merge_adapter(base: str, adapter_dir: str, out_dir: str, ollama_model_name: str, template_temperature: float = 0.05, hf_token: str | None = None, local_files_only: bool = False, trust_remote_code: bool = True, auto_base: bool = False):
76
+ out_path = Path(out_dir)
77
+ out_path.mkdir(parents=True, exist_ok=True)
78
+
79
+ # If requested, detect base from adapter_config.json
80
+ if auto_base or (isinstance(base, str) and base.lower() == "auto"):
81
+ detected = _detect_base_from_adapter(adapter_dir)
82
+ if detected:
83
+ print(f"[auto-base] Detected base model from adapter_config: {detected}")
84
+ base = detected
85
+ else:
86
+ raise RuntimeError("Could not auto-detect base model; supply --base explicitly.")
87
+
88
+ # Load the tokenizer first, it's small and fast
89
+ try:
90
+ tokenizer = AutoTokenizer.from_pretrained(base, local_files_only=local_files_only)
91
+ except Exception as e:
92
+ print(f"Failed loading tokenizer for base '{base}': {e}")
93
+ raise
94
+
95
+ # Configure 4-bit quantization with the necessary offload flag
96
+ quantization_config = BitsAndBytesConfig(
97
+ load_in_4bit=True,
98
+ bnb_4bit_quant_type="nf4",
99
+ bnb_4bit_compute_dtype=torch.float16,
100
+ bnb_4bit_use_double_quant=True,
101
+ llm_int8_enable_fp32_cpu_offload=True, # THIS IS CRUCIAL
102
+ )
103
+
104
+ print(f"Loading base model: {base} (using 4-bit quantization with auto device mapping) 🧠💡")
105
+
106
+ try:
107
+ # Use the BitsAndBytesConfig and let device_map="auto" handle the offloading
108
+ base_model = AutoModelForCausalLM.from_pretrained(
109
+ base,
110
+ quantization_config=quantization_config,
111
+ device_map="auto",
112
+ low_cpu_mem_usage=True,
113
+ local_files_only=local_files_only,
114
+ trust_remote_code=trust_remote_code,
115
+ )
116
+ except Exception as e:
117
+ print(f"Failed loading base model '{base}': {e}")
118
+ raise
119
+
120
+ print(f"Loading LoRA adapter from: {adapter_dir}")
121
+ peft_model = PeftModel.from_pretrained(base_model, adapter_dir)
122
+ print("LoRA adapter loaded.")
123
+
124
+ print("Merging LoRA weights into base weights (in-memory)...")
125
+ merged_model = peft_model.merge_and_unload()
126
+ print("Merge complete.")
127
+
128
+ print(f"Saving merged model to: {out_dir}")
129
+ merged_model.save_pretrained(out_dir)
130
+ tokenizer.save_pretrained(out_dir)
131
+
132
+ modelfile_lines = [
133
+ "FROM .",
134
+ f"PARAMETER temperature {template_temperature}",
135
+ 'TEMPLATE """{{ .Prompt }}"""',
136
+ "",
137
+ ]
138
+ (out_path / "Modelfile").write_text("\n".join(modelfile_lines), encoding="utf-8")
139
+
140
+ meta = {
141
+ "base": base,
142
+ "adapter_dir": adapter_dir,
143
+ "merged_dir": out_dir,
144
+ "ollama_model_name": ollama_model_name,
145
+ "temperature": template_temperature,
146
+ }
147
+ (out_path / "merge_metadata.json").write_text(json.dumps(meta, indent=2), encoding="utf-8")
148
+
149
+ print("Merge complete. Next steps:")
150
+ print(f" 1. ollama create {ollama_model_name} -f {out_dir}/Modelfile")
151
+ print(f" 2. Set FINETUNED_MODEL_NAME={ollama_model_name} in your environment")
152
+ print(" 3. Run your agent code again.")
153
+
154
+ def main():
155
+ parser = argparse.ArgumentParser(description="Merge a Qwen LoRA adapter for Ollama usage.")
156
+ parser.add_argument("--base", required=True, help="Base HF model id used during finetuning (default: qwen2.5:3b-instruct)")
157
+ parser.add_argument("--auto-base", action="store_true", help="Ignore --base value and read base from adapter_config.json")
158
+ parser.add_argument("--adapter-dir", required=True, help="Path to the LoRA adapter directory (with adapter_model.safetensors)")
159
+ parser.add_argument("--out-dir", required=True, help="Directory to write merged weights and Modelfile")
160
+ parser.add_argument("--ollama-model-name", required=True, help="Target Ollama model name to create")
161
+ parser.add_argument("--temperature", type=float, default=0.05, help="Default temperature for Modelfile")
162
+ parser.add_argument("--hf-token", help="Hugging Face access token (optional)")
163
+ parser.add_argument("--local-files-only", action="store_true", help="Do not attempt to download; require weights to be cached locally")
164
+ parser.add_argument("--no-trust-remote-code", action="store_true", help="Disable trust_remote_code (not recommended for some models)")
165
+ args = parser.parse_args()
166
+
167
+ hf_token = args.hf_token or os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN")
168
+
169
+ merge_adapter(
170
+ base=args.base,
171
+ adapter_dir=args.adapter_dir,
172
+ out_dir=args.out_dir,
173
+ ollama_model_name=args.ollama_model_name,
174
+ template_temperature=args.temperature,
175
+ hf_token=hf_token,
176
+ local_files_only=args.local_files_only,
177
+ trust_remote_code=not args.no_trust_remote_code,
178
+ )
179
+
180
+ if __name__ == "__main__":
181
+ main()
Agent/merged_model_test.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from safetensors.numpy import load_file
3
+ from pathlib import Path
4
+
5
+ base = Path(r"e:\Capstone_Project\text2sql-agent-mcp\merged_qwen2_5_3b_text2sql")
6
+ safetensor = base / "model.safetensors"
7
+ cfg_path = base / "config.json"
8
+
9
+ cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
10
+ hidden = cfg.get("hidden_size")
11
+ print("expected attn_q shape (hidden, hidden) =", hidden, hidden)
12
+
13
+ print("Loading safetensors (this may use RAM)...")
14
+ tensors = load_file(str(safetensor))
15
+
16
+ # find candidate keys
17
+ candidates = [k for k in tensors.keys() if "attn_q.weight" in k or "blk.0.attn_q.weight" in k]
18
+ if not candidates:
19
+ # also show some top-level keys to help debug
20
+ print("No attn_q keys found. Showing first 40 keys in the safetensor:")
21
+ for k in list(tensors.keys())[:40]:
22
+ print(" ", k)
23
+ else:
24
+ print("Found attn_q keys (showing up to 30):")
25
+ for k in candidates[:30]:
26
+ print(k, "->", tensors[k].shape, "dtype:", tensors[k].dtype)
Agent/migrate_to_neon.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ from sqlalchemy import create_engine, text
4
+ from sqlalchemy.engine import URL
5
+ import pandas as pd
6
+ from dotenv import load_dotenv
7
+
8
+ # Try to find .env in current dir and Agent dir
9
+ load_dotenv()
10
+ load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '.env'))
11
+ load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '..', '.env'))
12
+
13
+ # LOCAL_DB = "postgresql://postgres:postgres@localhost:5432/employee"
14
+ LOCAL_DB = os.environ.get("DB_CONNECTION_URL")
15
+ # NEON_DB = Your new Neon connection string
16
+ NEON_DB = os.environ.get("NEON_DB_URL")
17
+
18
+ async def migrate():
19
+ if not NEON_DB:
20
+ print("❌ Error: NEON_DB_URL not found in environment variables.")
21
+ return
22
+
23
+ print("🚀 Starting Cloud Migration to Neon.tech...")
24
+
25
+ # 1. Connect to Local
26
+ local_engine = create_engine(LOCAL_DB)
27
+
28
+ # 2. Connect to Neon (Ensure SSL)
29
+ neon_uri = NEON_DB
30
+ if 'sslmode=' not in neon_uri:
31
+ sep = '&' if '?' in neon_uri else '?'
32
+ neon_uri += f"{sep}sslmode=require"
33
+
34
+ neon_engine = create_engine(neon_uri)
35
+
36
+ tables = ["department", "employee", "dept_emp", "dept_manager", "salary", "title"]
37
+
38
+ for table in tables:
39
+ print(f"📦 Migrating table: {table}...")
40
+ try:
41
+ # Read data from local
42
+ df = pd.read_sql_table(table, local_engine)
43
+ print(f" - Found {len(df)} rows.")
44
+
45
+ # Write to Neon (replace if exists)
46
+ df.to_sql(table, neon_engine, if_exists='replace', index=False)
47
+ print(f" ✅ {table} successfully uploaded to Neon.")
48
+ except Exception as e:
49
+ print(f" ❌ Failed to migrate {table}: {e}")
50
+
51
+ print("\n🎉 Migration Complete! Your cloud database is ready.")
52
+
53
+ if __name__ == "__main__":
54
+ asyncio.run(migrate())
Agent/schema_profile.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import time
4
+ import uuid
5
+ import threading
6
+ from typing import Any, Dict, List, Optional
7
+
8
+
9
+ class SchemaProfile:
10
+ """
11
+ Runtime schema profile representing the active database.
12
+ Stores tables, columns, PK/FK metadata, row counts, sample rows, and
13
+ a digest string suitable for injecting into LLM prompts.
14
+ """
15
+
16
+ SAMPLE_ROW_LIMIT = 3
17
+ MAX_DIGEST_TABLES = 40
18
+ MAX_DIGEST_COLUMNS = 25
19
+
20
+ def __init__(self, name: str, db_url: Optional[str] = None, is_demo: bool = False):
21
+ self.name = name
22
+ self.db_url = db_url
23
+ self.is_demo = is_demo
24
+ self.tables: List[str] = []
25
+ self.columns_by_table: Dict[str, List[Dict[str, Any]]] = {}
26
+ self.pk_by_table: Dict[str, List[str]] = {}
27
+ self.fk_by_table: Dict[str, List[Dict[str, Any]]] = {}
28
+ self.row_counts: Dict[str, int] = {}
29
+ self.sample_rows: Dict[str, List[Dict[str, Any]]] = {}
30
+ self.available_tables_set: set = set()
31
+
32
+ @property
33
+ def is_employee_db(self) -> bool:
34
+ # Treat as employee demo if explicitly marked or name matches
35
+ if self.is_demo:
36
+ return True
37
+ n = (self.name or "").lower()
38
+ return "employee" in n or n == "demo_employee"
39
+
40
+ # ------------------------------------------------------------------
41
+ # Population
42
+ # ------------------------------------------------------------------
43
+ def populate_from_inspector(self, inspector: Any, engine: Optional[Any] = None) -> None:
44
+ """Fill all metadata from a SQLAlchemy inspector (and optionally sample
45
+ row counts / preview rows via a sync engine connection)."""
46
+ try:
47
+ tables = list(
48
+ t for t in (inspector.get_table_names() + inspector.get_view_names())
49
+ if not t.startswith("_")
50
+ )
51
+ except Exception as e:
52
+ print(f"[SCHEMA-PROFILE] inspector table listing failed: {e}")
53
+ tables = []
54
+
55
+ self.tables = sorted(tables)
56
+ self.available_tables_set = set(self.tables)
57
+ self.columns_by_table = {}
58
+ self.pk_by_table = {}
59
+ self.fk_by_table = {}
60
+
61
+ for t in self.tables:
62
+ try:
63
+ self.columns_by_table[t] = inspector.get_columns(t)
64
+ except Exception:
65
+ self.columns_by_table[t] = []
66
+ try:
67
+ pks = inspector.get_pk_constraint(t)
68
+ self.pk_by_table[t] = (pks or {}).get("constrained_columns", []) or []
69
+ except Exception:
70
+ self.pk_by_table[t] = []
71
+ try:
72
+ self.fk_by_table[t] = inspector.get_foreign_keys(t) or []
73
+ except Exception:
74
+ self.fk_by_table[t] = []
75
+
76
+ if engine is not None:
77
+ self._collect_row_stats(engine)
78
+
79
+ def _collect_row_stats(self, engine: Any) -> None:
80
+ """Best-effort row counts + small sample rows using a sync engine."""
81
+ from sqlalchemy import text as sql_text
82
+
83
+ self.row_counts = {}
84
+ self.sample_rows = {}
85
+ try:
86
+ with engine.connect() as conn:
87
+ for t in self.tables:
88
+ # Row count (quoted identifier first, unquoted fallback)
89
+ try:
90
+ cnt = conn.execute(sql_text(f'SELECT COUNT(*) FROM "{t}"')).scalar()
91
+ self.row_counts[t] = int(cnt) if cnt is not None else 0
92
+ except Exception:
93
+ try:
94
+ cnt = conn.execute(sql_text(f"SELECT COUNT(*) FROM {t}")).scalar()
95
+ self.row_counts[t] = int(cnt) if cnt is not None else 0
96
+ except Exception:
97
+ self.row_counts[t] = 0
98
+ # Sample rows
99
+ if self.row_counts.get(t, 0) > 0:
100
+ try:
101
+ result = conn.execute(
102
+ sql_text(f'SELECT * FROM "{t}" LIMIT {self.SAMPLE_ROW_LIMIT}')
103
+ )
104
+ rows = result.mappings().all()
105
+ self.sample_rows[t] = [
106
+ {k: _json_safe(v) for k, v in dict(r).items()} for r in rows
107
+ ]
108
+ except Exception:
109
+ try:
110
+ result = conn.execute(
111
+ sql_text(f"SELECT * FROM {t} LIMIT {self.SAMPLE_ROW_LIMIT}")
112
+ )
113
+ rows = result.mappings().all()
114
+ self.sample_rows[t] = [
115
+ {k: _json_safe(v) for k, v in dict(r).items()} for r in rows
116
+ ]
117
+ except Exception:
118
+ self.sample_rows[t] = []
119
+ else:
120
+ self.sample_rows[t] = []
121
+ except Exception as e:
122
+ print(f"[SCHEMA-PROFILE] row stats collection failed: {e}")
123
+
124
+ # ------------------------------------------------------------------
125
+ # Digest for LLM prompts
126
+ # ------------------------------------------------------------------
127
+ def build_digest(self, max_tables: Optional[int] = None) -> str:
128
+ max_tables = max_tables or self.MAX_DIGEST_TABLES
129
+ lines: List[str] = []
130
+ lines.append(f"Database schema name: {self.name}")
131
+ lines.append(f"Number of tables/views: {len(self.tables)}")
132
+ lines.append("Tables and columns:")
133
+ for t in self.tables[:max_tables]:
134
+ cols = self.columns_by_table.get(t, [])
135
+ col_parts = []
136
+ for c in cols[: self.MAX_DIGEST_COLUMNS]:
137
+ ctype = str(c.get("type", ""))[:24]
138
+ col_parts.append(f"{c.get('name')} {ctype}".strip())
139
+ colstr = ", ".join(col_parts) if col_parts else "(no columns)"
140
+ rc = self.row_counts.get(t)
141
+ lines.append(f" - {t} ({colstr}) [rows={rc if rc is not None else '?'}]")
142
+ fks = self.fk_by_table.get(t, [])
143
+ for fk in fks[:4]:
144
+ ref = fk.get("referred_table")
145
+ lcols = fk.get("constrained_columns") or []
146
+ rcols = fk.get("referred_columns") or []
147
+ if ref:
148
+ lines.append(f" FK: {lcols} -> {ref}({rcols})")
149
+ if len(cols) > self.MAX_DIGEST_COLUMNS:
150
+ lines.append(f" ... {len(cols) - self.MAX_DIGEST_COLUMNS} more columns")
151
+ if len(self.tables) > max_tables:
152
+ lines.append(f" ... {len(self.tables) - max_tables} more tables")
153
+ return "\n".join(lines)
154
+
155
+ def summarize(self) -> Dict[str, Any]:
156
+ """Compact JSON-friendly summary (for API responses / UI)."""
157
+ return {
158
+ "name": self.name,
159
+ "db_url": self.db_url,
160
+ "is_demo": self.is_demo,
161
+ "is_employee_db": self.is_employee_db,
162
+ "tables": [
163
+ {
164
+ "name": t,
165
+ "row_count": self.row_counts.get(t),
166
+ "columns": [c.get("name") for c in self.columns_by_table.get(t, [])],
167
+ "sample_rows": self.sample_rows.get(t, []),
168
+ }
169
+ for t in self.tables
170
+ ],
171
+ }
172
+
173
+
174
+ def _json_safe(v: Any) -> Any:
175
+ try:
176
+ json.dumps(v)
177
+ return v
178
+ except (TypeError, ValueError):
179
+ return str(v)
180
+
181
+
182
+ class ProfileRegistry:
183
+ """
184
+ Registry of user-registered database profiles.
185
+
186
+ Each registry entry stores lightweight metadata (id, name, db_url, kind).
187
+ Full introspection happens lazily when a profile is switched to (the
188
+ agent's initialize_database walks the schema at that moment).
189
+ """
190
+
191
+ def __init__(self, store_path: str):
192
+ self.store_path = store_path
193
+ self._lock = threading.Lock()
194
+ self.profiles: Dict[str, Dict[str, Any]] = {}
195
+ self.active_id: Optional[str] = None
196
+ self.load()
197
+
198
+ # ------------------------------------------------------------------
199
+ def load(self) -> None:
200
+ try:
201
+ if os.path.exists(self.store_path):
202
+ with open(self.store_path, "r", encoding="utf-8") as fh:
203
+ data = json.load(fh)
204
+ self.profiles = data.get("profiles", {})
205
+ self.active_id = data.get("active_id")
206
+ except Exception as e:
207
+ print(f"[PROFILE-REGISTRY] load failed: {e}")
208
+ self.profiles = {}
209
+ self.active_id = None
210
+
211
+ def save(self) -> None:
212
+ with self._lock:
213
+ try:
214
+ os.makedirs(os.path.dirname(self.store_path), exist_ok=True)
215
+ with open(self.store_path, "w", encoding="utf-8") as fh:
216
+ json.dump(
217
+ {"profiles": self.profiles, "active_id": self.active_id},
218
+ fh,
219
+ indent=2,
220
+ )
221
+ except Exception as e:
222
+ print(f"[PROFILE-REGISTRY] save failed: {e}")
223
+
224
+ # ------------------------------------------------------------------
225
+ def list(self) -> List[Dict[str, Any]]:
226
+ out = []
227
+ for pid, p in self.profiles.items():
228
+ out.append(
229
+ {
230
+ "id": pid,
231
+ "name": p.get("name"),
232
+ "kind": p.get("kind", "user"),
233
+ "db_url": p.get("db_url"),
234
+ "created_at": p.get("created_at"),
235
+ "active": pid == self.active_id,
236
+ }
237
+ )
238
+ return sorted(out, key=lambda p: (not p["active"], p.get("created_at") or 0))
239
+
240
+ def get(self, profile_id: str) -> Optional[Dict[str, Any]]:
241
+ return self.profiles.get(profile_id)
242
+
243
+ def active(self) -> Optional[Dict[str, Any]]:
244
+ if self.active_id and self.active_id in self.profiles:
245
+ return {"id": self.active_id, **self.profiles[self.active_id]}
246
+ return None
247
+
248
+ def add(
249
+ self,
250
+ name: str,
251
+ db_url: str,
252
+ kind: str = "user",
253
+ activate: bool = True,
254
+ ) -> Dict[str, Any]:
255
+ pid = uuid.uuid4().hex[:12]
256
+ entry = {
257
+ "name": name,
258
+ "db_url": db_url,
259
+ "kind": kind,
260
+ "created_at": time.time(),
261
+ }
262
+ with self._lock:
263
+ self.profiles[pid] = entry
264
+ if activate or self.active_id is None:
265
+ self.active_id = pid
266
+ self.save()
267
+ return {"id": pid, **entry}
268
+
269
+ def remove(self, profile_id: str) -> bool:
270
+ with self._lock:
271
+ if profile_id not in self.profiles:
272
+ return False
273
+ del self.profiles[profile_id]
274
+ if self.active_id == profile_id:
275
+ self.active_id = next(iter(self.profiles), None)
276
+ self.save()
277
+ return True
278
+
279
+ def switch(self, profile_id: str) -> Optional[Dict[str, Any]]:
280
+ with self._lock:
281
+ if profile_id not in self.profiles:
282
+ return None
283
+ self.active_id = profile_id
284
+ self.save()
285
+ return {"id": profile_id, **self.profiles[profile_id]}
Agent/test_adapter_weights.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Set environment variables BEFORE importing torch
3
+ import os
4
+ os.environ["TORCHINDUCTOR_DISABLE"] = "1"
5
+ os.environ["TORCH_COMPILE_DISABLE"] = "1"
6
+ # Optional: force a specific GPU (uncomment if needed)
7
+ # os.environ["CUDA_VISIBLE_DEVICES"] = "0"
8
+
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer
10
+ from peft import PeftModel
11
+ import torch
12
+
13
+ # In-code disables for torch.compile and inductor/triton
14
+ torch._dynamo.config.suppress_errors = True
15
+ #torch._dynamo.config.enable = False
16
+ torch.set_float32_matmul_precision('high')
17
+
18
+ #base = "google/gemma-3-1b-it"
19
+ #adapter = "Agent/Gemma3_1B_weights"
20
+ base = "Qwen/Qwen2.5-3B-Instruct"
21
+ adapter = "Agent/Qwen2.5_3b_weights"
22
+ model = AutoModelForCausalLM.from_pretrained(
23
+ base,
24
+ dtype="auto",
25
+ device_map=None,
26
+ load_in_8bit=True,
27
+ low_cpu_mem_usage=True,
28
+ local_files_only=False # Set to False to force download if needed
29
+ #trust_remote_code=True
30
+ )
31
+ model = PeftModel.from_pretrained(model, adapter, local_files_only=True)
32
+ model = model.to("cuda") # Move model to GPU
33
+ tokenizer = AutoTokenizer.from_pretrained(base)
34
+
35
+ prompt = "Schema: employee(emp_no, birth_date, first_name, last_name, gender, hire_date),\n" \
36
+ "department(dept_no, dept_name),\n" \
37
+ "dept_emp(emp_no, dept_no, from_date, to_date),\n" \
38
+ "salary(emp_no, salary, from_date, to_date),\n" \
39
+ "Write PostgreSQL query for highest and lowest salary across all departments. Do not include any explanation."
40
+ inputs = tokenizer(prompt, return_tensors="pt")
41
+ # Move all input tensors to CUDA
42
+ inputs = {k: v.to("cuda") for k, v in inputs.items()}
43
+
44
+ output = model.generate(**inputs, max_new_tokens=1028)
45
+ print(tokenizer.decode(output[0], skip_special_tokens=True))
Agent/test_merged_model.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from safetensors.numpy import load_file
2
+ from pathlib import Path
3
+
4
+ base = Path(r"e:\Capstone_Project\text2sql-agent-mcp\merged_qwen2_5_3b_text2sql")
5
+ safetensor = base / "model.safetensors"
6
+
7
+ print("Loading safetensors (may use RAM)...")
8
+ d = load_file(str(safetensor))
9
+
10
+ weights = [k for k in d.keys() if k.endswith(".weight")]
11
+ print("weight keys count:", len(weights))
12
+
13
+ if weights:
14
+ for k in weights[:200]:
15
+ print(k, d[k].shape, d[k].dtype)
16
+ else:
17
+ print("\nNo '.weight' keys found — showing first 120 keys:")
18
+ for k in list(d.keys())[:120]:
19
+ print(k)
Agent/test_query_runner.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import os
3
+ import sys
4
+ # Ensure Agent package path is importable
5
+ sys.path.insert(0, r"e:/Capstone_Project/text2sql-agent-mcp/Agent")
6
+ import backups.agentic_workflow4 as aw
7
+
8
+ async def run_one():
9
+ # Initialize DB (use the module's configured DB_CONNECTION_URL when available)
10
+ db_uri = os.environ.get('DB_CONNECTION_URL') or getattr(aw, 'DB_CONNECTION_URL', None)
11
+ await aw.initialize_database(db_uri)
12
+ # Run a single question
13
+ # Prefix with 're-execute' to force regeneration and bypass any cached error in memory
14
+ res = await aw.agentic_query_process('re-execute Who are the top 10 highest-paid employees?')
15
+ print('\n--- AGENT OUTPUT START ---')
16
+ print(res)
17
+ print('--- AGENT OUTPUT END ---')
18
+
19
+ if __name__ == '__main__':
20
+ asyncio.run(run_one())
Agent/tools/document_scanner.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ try:
3
+ # Ensure local .env values (OLLAMA_*) are loaded when this module is imported
4
+ from dotenv import load_dotenv
5
+ load_dotenv()
6
+ except Exception:
7
+ pass
8
+ import uuid
9
+ import re
10
+ import base64
11
+ from typing import Dict, Any, Optional
12
+
13
+ def _mock_result(received: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
14
+ out = {"doc_id": str(uuid.uuid4()), "text": "(mock OCR output)", "metadata": {"pages": 1, "confidence": 0.0}}
15
+ if received:
16
+ out["received_args"] = received
17
+ return out
18
+
19
+
20
+ def clean_ocr_text(raw: Optional[str]) -> str:
21
+ """Lightweight post-processing for OCR output to improve readability.
22
+
23
+ - turns literal "\\n" sequences into real newlines
24
+ - unescapes common unicode/HTML escapes when safe
25
+ - collapses repeated spaces and blank lines
26
+ - trims and merges lines that were broken mid-sentence
27
+ """
28
+ if not raw:
29
+ return ""
30
+ s = raw
31
+ try:
32
+ # Convert literal backslash-n to actual newline
33
+ s = s.replace('\\n', '\n')
34
+ except Exception:
35
+ pass
36
+
37
+ # Try to interpret common escape sequences (conservative)
38
+ try:
39
+ s_decoded = s.encode('utf-8', errors='surrogatepass').decode('unicode_escape')
40
+ # Accept decoded result if it reduces backslash artifacts
41
+ if '\\n' not in s_decoded:
42
+ s = s_decoded
43
+ except Exception:
44
+ pass
45
+
46
+ # Normalize line endings and whitespace
47
+ s = s.replace('\r\n', '\n').replace('\r', '\n')
48
+ s = re.sub(r'[ \t]{2,}', ' ', s)
49
+ # Collapse 3+ newlines into max 2
50
+ s = re.sub(r'\n{3,}', '\n\n', s)
51
+
52
+ # Trim whitespace on each line
53
+ lines = [ln.strip() for ln in s.splitlines()]
54
+
55
+ # Merge lines that likely were broken mid-sentence: if a line doesn't end with
56
+ # sentence punctuation and the next line begins with a lowercase letter or digit,
57
+ # join them with a space.
58
+ merged = []
59
+ i = 0
60
+ while i < len(lines):
61
+ line = lines[i]
62
+ if i < len(lines) - 1:
63
+ nxt = lines[i + 1]
64
+ if line and nxt and not re.search(r'[\.\!\?\:;]$', line) and re.match(r'^[a-z0-9]', nxt):
65
+ line = line + ' ' + nxt
66
+ i += 2
67
+ # Continue merging subsequent similar lines
68
+ while i < len(lines) and lines[i] and not re.search(r'[\.\!\?\:;]$', line) and re.match(r'^[a-z0-9]', lines[i]):
69
+ line = line + ' ' + lines[i]
70
+ i += 1
71
+ merged.append(line)
72
+ continue
73
+ merged.append(line)
74
+ i += 1
75
+
76
+ s = '\n'.join([ln for ln in merged if ln])
77
+
78
+ # Remove long runs of underscores or pipes
79
+ s = re.sub(r'[_\|]{2,}', '', s)
80
+
81
+ # Strip control chars except common whitespace
82
+ s = ''.join(ch for ch in s if ord(ch) >= 9 and ord(ch) != 11 and ord(ch) != 12)
83
+
84
+ try:
85
+ import html
86
+
87
+ s = html.unescape(s)
88
+ except Exception:
89
+ pass
90
+
91
+ # Decode literal unicode escapes like \u0027 -> ' and \xA4 -> currency symbol
92
+ try:
93
+ def _u_decode(m):
94
+ code = m.group(1)
95
+ try:
96
+ return chr(int(code, 16))
97
+ except Exception:
98
+ return m.group(0)
99
+
100
+ s = re.sub(r'\\u([0-9A-Fa-f]{4})', _u_decode, s)
101
+ s = re.sub(r'\\x([0-9A-Fa-f]{2})', lambda m: chr(int(m.group(1), 16)), s)
102
+ except Exception:
103
+ pass
104
+
105
+ # Remove stray leading 'n' characters that appear before uppercase words (common OCR/newline artifact)
106
+ try:
107
+ s = re.sub(r'(?<=\s|^)[nN](?=[A-Z])', '', s)
108
+ except Exception:
109
+ pass
110
+
111
+ # Ensure space after commas when missing
112
+ try:
113
+ s = re.sub(r',(?=[^\s])', ', ', s)
114
+ except Exception:
115
+ pass
116
+
117
+ # Remove spaces before punctuation
118
+ try:
119
+ s = re.sub(r'\s+([,\.\:\;\%])', r'\1', s)
120
+ except Exception:
121
+ pass
122
+
123
+ # Attempt to fix common mojibake (double-encoded UTF-8) conservatively.
124
+ # Only apply if there are visible 'Ã' sequences suggesting encoding issues.
125
+ try:
126
+ if 'Ã' in s or 'Â' in s:
127
+ try:
128
+ candidate = s.encode('latin-1').decode('utf-8')
129
+ # Accept candidate if it reduces suspicious sequences
130
+ if candidate.count('Ã') < s.count('Ã'):
131
+ s = candidate
132
+ except Exception:
133
+ pass
134
+ except Exception:
135
+ pass
136
+
137
+ return s.strip()
138
+
139
+
140
+ def process_image(image_url: Optional[str] = None, image_bytes: Optional[bytes] = None, options: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
141
+ """Process an image using local OCR first (pytesseract), with a light transformers fallback.
142
+
143
+ Accepts either `image_url` or `image_bytes` (bytes or base64 string). Returns dict: {doc_id, text, metadata}
144
+ """
145
+
146
+ # Lightweight imports that may be missing in minimal environments
147
+ try:
148
+ from PIL import Image
149
+ from io import BytesIO
150
+ import requests
151
+ except Exception:
152
+ # Missing imaging/network deps -> return mock with echo of args
153
+ return _mock_result(received={"image_url": image_url, "has_bytes": bool(image_bytes)})
154
+
155
+ # Normalize image_bytes if base64 string was passed
156
+ if isinstance(image_bytes, str):
157
+ try:
158
+ image_bytes = base64.b64decode(image_bytes)
159
+ except Exception:
160
+ image_bytes = None
161
+
162
+ # Acquire PIL image
163
+ img = None
164
+ try:
165
+ if image_bytes:
166
+ img = Image.open(BytesIO(image_bytes)).convert("RGB")
167
+ elif image_url:
168
+ resp = requests.get(image_url, timeout=15)
169
+ resp.raise_for_status()
170
+ img = Image.open(BytesIO(resp.content)).convert("RGB")
171
+ else:
172
+ return _mock_result(received={"image_url": image_url, "has_bytes": False})
173
+ except Exception:
174
+ return _mock_result(received={"image_url": image_url, "has_bytes": bool(image_bytes)})
175
+
176
+ # PRIORITY: Try local Tesseract (pytesseract) first — lightweight and deterministic on Windows
177
+
178
+ try:
179
+ import pytesseract
180
+ # Robustly find tesseract executable: prefer PATH, then common Windows install locations
181
+ try:
182
+ import shutil
183
+ found = shutil.which('tesseract')
184
+ except Exception:
185
+ found = None
186
+ if not found:
187
+ # common install locations on Windows
188
+ for candidate in (r"C:\Program Files\Tesseract-OCR\tesseract.exe", r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"):
189
+ try:
190
+ if os.path.exists(candidate):
191
+ found = candidate
192
+ break
193
+ except Exception:
194
+ continue
195
+ try:
196
+ if found:
197
+ pytesseract.pytesseract.tesseract_cmd = found
198
+ print(f"[document_scanner] using tesseract executable: {found}")
199
+ else:
200
+ # leave default; pytesseract will raise a helpful error which we catch below
201
+ print("[document_scanner] tesseract executable not found in PATH or common locations")
202
+ except Exception:
203
+ # ignore assignment errors and let pytesseract raise on use
204
+ pass
205
+
206
+ try:
207
+ if img is not None:
208
+ print("[document_scanner] attempting PRIMARY pytesseract OCR")
209
+ ttxt = pytesseract.image_to_string(img)
210
+ if ttxt and ttxt.strip():
211
+ print(f"[document_scanner] pytesseract returned text (len={len(ttxt.strip())})")
212
+ return {"doc_id": str(uuid.uuid4()), "text": clean_ocr_text(ttxt), "metadata": {"pages": 1, "confidence": None}}
213
+ else:
214
+ print("[document_scanner] pytesseract returned no text; falling through to model-based fallbacks")
215
+ except Exception as e_pyt_first:
216
+ print(f"[document_scanner] primary pytesseract attempt failed: {e_pyt_first}")
217
+ except Exception:
218
+ # pytesseract not installed in environment — continue to available backends
219
+ pass
220
+
221
+ # Last resort: return a safe mock that echoes inputs
222
+ # (Tesseract failed or is not installed — Q&A will still work via Granite Vision if image is saved)
223
+ return _mock_result(received={"image_url": image_url, "has_bytes": bool(image_bytes)})
Agent/tools/granite_vision.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Vision MCP tool - visual Q&A via Groq Vision API.
3
+
4
+ Cloud path : image -> Groq Vision -> structured answer
5
+ Local path : image -> Ollama qwen2-vl -> answer (dev only)
6
+
7
+ Registered in mcp_server.py as 'granite_vision.qa'.
8
+ """
9
+ import os
10
+ import base64
11
+ import requests
12
+ from typing import Optional
13
+
14
+
15
+ def qa(image_path: str, question: str, model_path: Optional[str] = None) -> dict:
16
+ """Answer a question about a document image using Groq Vision or local Ollama."""
17
+
18
+ print(f"[vision.qa] image={image_path} question={question[:80]}")
19
+
20
+ # CLOUD MODE: Groq Vision API
21
+ if os.environ.get("USE_HF_CLOUD", "0") in ("1", "true", "True"):
22
+ groq_key = os.environ.get("GROQ_API_KEY")
23
+ groq_model = os.environ.get("GROQ_VISION_MODEL", "qwen/qwen3.8-27b")
24
+
25
+ if groq_key:
26
+ print(f"[granite_vision.qa] CLOUD MODE: {groq_model} via Groq")
27
+ try:
28
+ from groq import Groq
29
+
30
+ client = Groq(api_key=groq_key)
31
+
32
+ with open(image_path, "rb") as f:
33
+ img_b64 = base64.b64encode(f.read()).decode("utf-8")
34
+
35
+ ext = os.path.splitext(image_path)[-1].lower().lstrip(".")
36
+ mime = "image/jpeg" if ext in ("jpg", "jpeg") else f"image/{ext}"
37
+
38
+ response = client.chat.completions.create(
39
+ model=groq_model,
40
+ messages=[
41
+ {
42
+ "role": "user",
43
+ "content": [
44
+ {
45
+ "type": "text",
46
+ "text": (
47
+ "You are analyzing a document image. "
48
+ "Look carefully at the layout, tables, numbers, and text. "
49
+ "Answer the following question based only on what you see:\n\n"
50
+ + question
51
+ )
52
+ },
53
+ {
54
+ "type": "image_url",
55
+ "image_url": {
56
+ "url": f"data:{mime};base64,{img_b64}"
57
+ }
58
+ }
59
+ ]
60
+ }
61
+ ],
62
+ max_tokens=1024,
63
+ temperature=0.1
64
+ )
65
+
66
+ answer = response.choices[0].message.content.strip()
67
+ print(f"[granite_vision.qa] Groq answer ({len(answer)} chars): {answer[:200]}")
68
+ return {"answer": answer, "model": f"{groq_model} (Groq Vision)"}
69
+
70
+ except Exception as e:
71
+ print(f"[granite_vision.qa] Groq failed: {e}")
72
+ return {
73
+ "answer": f"Groq Vision error: {e}",
74
+ "model": groq_model,
75
+ "error": str(e)
76
+ }
77
+ else:
78
+ print("[granite_vision.qa] GROQ_API_KEY not set in HF secrets.")
79
+ return {
80
+ "answer": "GROQ_API_KEY is not configured. Please add it in HuggingFace Space secrets.",
81
+ "model": "none",
82
+ "error": "missing_groq_key"
83
+ }
84
+
85
+ # LOCAL MODE (dev only): Ollama
86
+ local_model = os.environ.get("GRANITE_MODEL_PATH", "qwen2-vl:2b")
87
+ print(f"[granite_vision.qa] LOCAL MODE: sending image to Ollama ({local_model})")
88
+
89
+ try:
90
+ with open(image_path, "rb") as f:
91
+ img_b64 = base64.b64encode(f.read()).decode("utf-8")
92
+
93
+ base_url = os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434").rstrip("/")
94
+ url = f"{base_url}/api/chat"
95
+ payload = {
96
+ "model": local_model,
97
+ "messages": [
98
+ {
99
+ "role": "user",
100
+ "content": f"Carefully analyze this document image. {question}",
101
+ "images": [img_b64]
102
+ }
103
+ ],
104
+ "stream": False,
105
+ "keep_alive": 60,
106
+ "options": {"num_ctx": 1024, "temperature": 0.1}
107
+ }
108
+ r = requests.post(url, json=payload, timeout=300)
109
+ if r.status_code == 200:
110
+ answer = r.json().get("message", {}).get("content", "").strip()
111
+ print(f"[granite_vision.qa] Ollama answer ({len(answer)} chars): {answer[:200]}")
112
+ return {"answer": answer, "model": f"{local_model} (Ollama)"}
113
+ else:
114
+ msg = f"Ollama HTTP {r.status_code}: {r.text}"
115
+ print(f"[granite_vision.qa] {msg}")
116
+ return {"answer": msg, "model": f"{local_model} (Ollama)", "error": "http_error"}
117
+
118
+ except Exception as e:
119
+ msg = f"[ERROR] Ollama Q&A failed: {e}"
120
+ print(f"[granite_vision.qa] {msg}")
121
+ return {"answer": msg, "model": f"{local_model} (Ollama)", "error": str(e)}
Agent/tools/groq_vision_health.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import base64
4
+ from typing import Optional
5
+
6
+
7
+ def health_check() -> dict:
8
+ """
9
+ Quick health check for Groq Vision model.
10
+ Returns {"ok": bool, "model": str, "error": Optional[str]}
11
+ """
12
+ if os.environ.get("USE_HF_CLOUD", "0") not in ("1", "true", "True"):
13
+ return {"ok": True, "model": "local-ollama", "error": None}
14
+
15
+ groq_key = os.environ.get("GROQ_API_KEY")
16
+ if not groq_key:
17
+ return {"ok": False, "model": "none", "error": "GROQ_API_KEY is not set"}
18
+
19
+ groq_model = os.environ.get("GROQ_VISION_MODEL", "qwen/qwen3.8-27b")
20
+ try:
21
+ from groq import Groq
22
+
23
+ client = Groq(api_key=groq_key)
24
+ # Try a minimal text-only call to verify model exists and is accessible
25
+ response = client.chat.completions.create(
26
+ model=groq_model,
27
+ messages=[{"role": "user", "content": "ping"}],
28
+ max_tokens=1,
29
+ temperature=0,
30
+ )
31
+ return {"ok": True, "model": groq_model, "error": None}
32
+ except Exception as e:
33
+ return {"ok": False, "model": groq_model, "error": str(e)}
Agent/worker.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ import io
4
+ import sys
5
+ import contextlib
6
+ from fastapi import FastAPI, HTTPException
7
+ from pydantic import BaseModel
8
+ from typing import Optional
9
+ from fastapi import File, UploadFile
10
+ import base64
11
+ import uuid
12
+ import uvicorn
13
+
14
+ # Worker that imports the agent and exposes a simple HTTP API
15
+ app = FastAPI(title="Agent Worker")
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # Schema profile registry (dynamic multi-DB support)
19
+ # ---------------------------------------------------------------------------
20
+ try:
21
+ from .schema_profile import ProfileRegistry
22
+ except Exception:
23
+ import Agent.schema_profile as _sp
24
+ ProfileRegistry = _sp.ProfileRegistry
25
+
26
+ SCHEMAS_DIR = os.path.join("uploads", "schemas")
27
+ PROFILE_STORE_PATH = os.path.join("chat_store", "schema_profiles.json")
28
+ profile_registry = ProfileRegistry(PROFILE_STORE_PATH)
29
+
30
+ SUPPORTED_DB_SUFFIXES = {".sqlite", ".db", ".sqlite3", ".csv"}
31
+
32
+
33
+ class AddSchemaJsonReq(BaseModel):
34
+ name: str
35
+ connection_url: str
36
+ activate: Optional[bool] = True
37
+
38
+
39
+ def _detect_demo_kind(name: str, tblset: Optional[set] = None) -> str:
40
+ """Classify a profile as the built-in employee demo or a user schema."""
41
+ n = (name or "").lower()
42
+ if "demo_employee" in n:
43
+ return "demo"
44
+ if tblset and all(
45
+ t in tblset for t in ["employee", "department", "salary", "dept_emp"]
46
+ ):
47
+ return "demo"
48
+ # Connection URL pointing at employee-ish database
49
+ if "employee" in (name or ""):
50
+ return "demo"
51
+ return "user"
52
+
53
+ class QueryReq(BaseModel):
54
+ question: str
55
+ doc_id: Optional[str] = None
56
+ mode: Optional[str] = None # 'text2sql' or 'ocr_qa'
57
+
58
+
59
+ class UploadResp(BaseModel):
60
+ doc_id: str
61
+ text_preview: str
62
+ image_url: str
63
+
64
+ class OcrQAReq(BaseModel):
65
+ question: str
66
+ doc_id: str
67
+
68
+ class OcrQAResp(BaseModel):
69
+ doc_id: str
70
+ answer: str
71
+ used_llm: bool
72
+
73
+ # Lazy import agent module (do at startup so heavy init happens in worker)
74
+ agent = None
75
+ # Lock to prevent concurrent capture of stdout/stderr which would interleave logs
76
+ capture_lock = asyncio.Lock()
77
+
78
+ @app.on_event("startup")
79
+ async def startup_event():
80
+ global agent
81
+ # Import here so the LLM and DB init occur inside the worker process
82
+ # Use package-relative import so we load Agent.agentic_workflow (not a top-level file)
83
+ try:
84
+ from . import agentic_workflow as agentic_workflow
85
+ except Exception:
86
+ # fallback to absolute package import
87
+ import Agent.agentic_workflow as agentic_workflow
88
+ agent = agentic_workflow
89
+
90
+ # ------------------------------------------------------------------
91
+ # Built-in demo employee database: ALWAYS available as a profile.
92
+ # Sourced from the authentic employees sample dataset bundled in the repo
93
+ # (employee-sample-database/sqlite/dataset_small/employee.db). Used as the
94
+ # active database out of the box when no DB_CONNECTION_URL is provided.
95
+ # ------------------------------------------------------------------
96
+ demo_db_url = None
97
+ demo_db_path = os.path.join(
98
+ os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
99
+ "employee-sample-database", "sqlite", "dataset_small", "employee.db",
100
+ )
101
+ if os.path.isfile(demo_db_path):
102
+ demo_db_url = f"sqlite:///{demo_db_path.replace(os.sep, '/')}"
103
+ try:
104
+ has_demo = any((p or {}).get("kind") == "demo"
105
+ for p in profile_registry.profiles.values())
106
+ if not has_demo:
107
+ profile_registry.add(name="demo_employee", db_url=demo_db_url,
108
+ kind="demo", activate=False)
109
+ print("[WORKER] Registered built-in demo profile 'demo_employee'")
110
+ except Exception as reg_err:
111
+ print(f"[WORKER] demo profile registration skipped: {reg_err}")
112
+ else:
113
+ print(f"[WORKER] Bundled demo employee DB not found at {demo_db_path}")
114
+
115
+ # ------------------------------------------------------------------
116
+ # Decide which database to initialize against:
117
+ # 1. DB_CONNECTION_URL (env/compose wins) 2. last active profile 3. demo
118
+ # ------------------------------------------------------------------
119
+ db_url = os.environ.get("DB_CONNECTION_URL")
120
+ active = profile_registry.active()
121
+ target_uri = db_url or (active or {}).get("db_url") or demo_db_url
122
+
123
+ if target_uri:
124
+ try:
125
+ await agent.initialize_database(uri=target_uri)
126
+ # Keep the registry's active entry in sync with what we connected to.
127
+ try:
128
+ if profile_registry.active_id is None:
129
+ prof = getattr(agent, "ACTIVE_SCHEMA_PROFILE", None)
130
+ _kind = "demo" if (prof and prof.is_employee_db) else "user"
131
+ pid = f"boot_{uuid.uuid4().hex[:8]}"
132
+ profile_registry.profiles[pid] = {
133
+ "name": (prof.name if prof else "startup_db") or "startup_db",
134
+ "db_url": target_uri,
135
+ "kind": _kind,
136
+ "created_at": __import__("time").time(),
137
+ }
138
+ profile_registry.active_id = pid
139
+ profile_registry.save()
140
+ print(f"[WORKER] Registered active schema profile '{pid}' for {target_uri}")
141
+ else:
142
+ # point the active id at the profile that owns target_uri
143
+ entries = profile_registry.list()
144
+ match = next((p for p in entries if (p.get("db_url") or "").replace("\\", "/") == target_uri.replace("\\", "/")), None)
145
+ if match and profile_registry.active_id != match["id"]:
146
+ profile_registry.switch(match["id"])
147
+ print(f"[WORKER] Active profile switched to '{match['name']}'")
148
+ except Exception as reg_err:
149
+ print(f"[WORKER] profile bootstrap skipped: {reg_err}")
150
+ except Exception as e:
151
+ # Log but continue; agentic_workflow has fallback behavior
152
+ print(f"Worker: initialize_database failed: {e}")
153
+ else:
154
+ print("Worker: no database available (no env DB, no profiles, no demo bundle)")
155
+ # Optional Groq Vision health check in cloud mode
156
+ try:
157
+ from .tools import groq_vision_health
158
+ hc = groq_vision_health.health_check()
159
+ if not hc.get("ok", True):
160
+ print(f"[WORKER] Groq Vision health warning: {hc.get('error')} (model={hc.get('model')})")
161
+ else:
162
+ print(f"[WORKER] Groq Vision health: ok (model={hc.get('model')})")
163
+ except Exception as e:
164
+ print(f"[WORKER] Groq Vision health check skipped: {e}")
165
+
166
+ @app.get("/health")
167
+ async def health():
168
+ return {"status": "ok"}
169
+
170
+
171
+ @app.post("/query")
172
+ async def query(req: QueryReq):
173
+ global agent
174
+ if agent is None:
175
+ raise HTTPException(status_code=503, detail="Agent not initialized")
176
+ q = req.question
177
+ doc_id = getattr(req, 'doc_id', None)
178
+ mode = getattr(req, 'mode', None)
179
+ # Capture stdout/stderr produced by the agent for this request
180
+ buf_out = io.StringIO()
181
+ buf_err = io.StringIO()
182
+ async with capture_lock:
183
+ try:
184
+ with contextlib.redirect_stdout(buf_out), contextlib.redirect_stderr(buf_err):
185
+ # Robust mode switch: if mode is 'ocr_qa' or doc_id is present, use OCR agent; else use SQL logic
186
+ if (mode == 'ocr_qa') or (doc_id and (mode is None or mode == 'auto')):
187
+ # Use OCR Q&A agent
188
+ # ocr_agent_qa may be sync, so run in executor
189
+ import asyncio
190
+ answer = await asyncio.get_event_loop().run_in_executor(
191
+ None, lambda: agent.ocr_agent_qa(q, doc_id)
192
+ )
193
+ result = answer
194
+ sql_out = None # No SQL for OCR Q&A
195
+ else:
196
+ # Use standard Text-to-SQL agentic workflow
197
+ result = await agent.agentic_query_process(q, None)
198
+ try:
199
+ sql_out = getattr(agent, 'LAST_GENERATED_SQL', None)
200
+ except Exception:
201
+ sql_out = None
202
+ except ValueError as ve:
203
+ # Treat known generation failures as normal answers so UI doesn't show nested JSON error
204
+ err_msg = str(ve)
205
+ if "Unable to generate SQL query" in err_msg:
206
+ result = err_msg # Provide user-visible plain text
207
+ sql_out = None
208
+ else:
209
+ import traceback
210
+ traceback.print_exc(file=buf_err)
211
+ raise HTTPException(status_code=500, detail=err_msg)
212
+ except Exception as e:
213
+ import traceback
214
+ traceback.print_exc(file=buf_err)
215
+ raise HTTPException(status_code=500, detail=str(e))
216
+ logs = buf_out.getvalue()
217
+ errlogs = buf_err.getvalue()
218
+ if errlogs:
219
+ logs = logs + "\n" + errlogs
220
+ # Chart contract: strip the embedded chart marker from the answer and
221
+ # expose it as a first-class field for the web UI (ECharts).
222
+ chart_out = None
223
+ try:
224
+ from .chart_contract import extract_chart_marker
225
+ clean_answer, chart_out = extract_chart_marker(result)
226
+ if chart_out is not None:
227
+ result = clean_answer
228
+ except Exception:
229
+ chart_out = None
230
+ return {"answer": result, "logs": logs, "sql": sql_out, "chart": chart_out}
231
+
232
+
233
+ @app.post("/ocr-qa", response_model=OcrQAResp)
234
+ async def ocr_qa(req: OcrQAReq):
235
+ """Answer a question about a previously uploaded document using its doc_id.
236
+
237
+ This uses the agent's ocr_agent_qa helper which pulls stored OCR text and
238
+ consults the LLM (or returns a low-memory fallback excerpt).
239
+ """
240
+ global agent
241
+ if agent is None:
242
+ raise HTTPException(status_code=503, detail="Agent not initialized")
243
+ question = req.question
244
+ doc_id = req.doc_id
245
+ # Run potentially blocking OCR QA in thread pool if it's sync
246
+ try:
247
+ answer = await asyncio.get_event_loop().run_in_executor(
248
+ None, lambda: agent.ocr_agent_qa(question, doc_id)
249
+ )
250
+ except Exception as e:
251
+ raise HTTPException(status_code=500, detail=f"ocr_qa failed: {e}")
252
+ used_llm = not answer.startswith("[Low memory]") and not answer.startswith("No OCR text") and not answer.startswith("Error while")
253
+ return OcrQAResp(doc_id=doc_id, answer=answer, used_llm=used_llm)
254
+
255
+
256
+ @app.post("/upload-image", response_model=UploadResp)
257
+ async def upload_image(file: UploadFile = File(...)):
258
+ """Accept an image, save locally, call MCP document_scanner.process eagerly,
259
+ persist OCR to private chat store, and return a doc_id plus preview.
260
+ """
261
+ global agent
262
+ if agent is None:
263
+ raise HTTPException(status_code=503, detail="Agent not initialized")
264
+
265
+ # Ensure uploads directory exists
266
+ uploads_dir = "uploads"
267
+ os.makedirs(uploads_dir, exist_ok=True)
268
+
269
+ # Save uploaded file
270
+ filename = f"{uuid.uuid4()}_{file.filename}"
271
+ path = os.path.join(uploads_dir, filename)
272
+ try:
273
+ contents = await file.read()
274
+ with open(path, "wb") as f:
275
+ f.write(contents)
276
+ except Exception as e:
277
+ raise HTTPException(status_code=500, detail=f"Failed to save upload: {e}")
278
+
279
+ # Call MCP document_scanner tool eagerly with base64 payload to avoid exposing file server
280
+ b64 = base64.b64encode(contents).decode('utf-8')
281
+ try:
282
+ from .mcp_client import mcp_call_tool
283
+ ctx = {"tool_call": {"name": "document_scanner.process", "args": {"image_bytes": b64}}}
284
+ resp = mcp_call_tool(prompt="run document scanner", timeout=60.0, context=ctx)
285
+ # Expect tool_result in response
286
+ tool_result = resp.get("tool_result") if isinstance(resp, dict) else None
287
+ except Exception:
288
+ # Fall back to local direct call if MCP unavailable or tool failed
289
+ tool_result = None
290
+ try:
291
+ if agent and hasattr(agent, 'tools') and hasattr(agent.tools, 'document_scanner'):
292
+ try:
293
+ tool_result = agent.tools.document_scanner.process_image(image_bytes=b64)
294
+ except Exception:
295
+ tool_result = None
296
+ except Exception:
297
+ tool_result = None
298
+ if not tool_result:
299
+ tool_result = {"doc_id": str(uuid.uuid4()), "text": "(ocr unavailable)", "metadata": {}}
300
+
301
+ # Persist OCR to private chat store file for retrieval by doc_id
302
+ doc_id = tool_result.get("doc_id") if isinstance(tool_result, dict) and tool_result.get("doc_id") else str(uuid.uuid4())
303
+ ocr_text = tool_result.get("text", "") if isinstance(tool_result, dict) else str(tool_result)
304
+
305
+ # Save to docs/ and also to chat_store_private for history
306
+ docs_dir = os.path.join("chat_store", "docs")
307
+ os.makedirs(docs_dir, exist_ok=True)
308
+ doc_path = os.path.join(docs_dir, f"{doc_id}.txt")
309
+ try:
310
+ with open(doc_path, "w", encoding="utf-8") as df:
311
+ df.write(ocr_text)
312
+ except Exception as e:
313
+ print(f"Failed to persist OCR text: {e}")
314
+
315
+ # Also persist the original image path so Granite Vision can do direct visual Q&A
316
+ img_path_file = os.path.join(docs_dir, f"{doc_id}.img_path")
317
+ try:
318
+ abs_img_path = os.path.abspath(path)
319
+ with open(img_path_file, "w", encoding="utf-8") as ipf:
320
+ ipf.write(abs_img_path)
321
+ print(f"[upload] Saved image path for doc_id={doc_id}: {abs_img_path}")
322
+ except Exception as e:
323
+ print(f"[upload] Failed to persist image path: {e}")
324
+
325
+ # Also add a short entry to chat_store_private for traceability
326
+ try:
327
+ try:
328
+ from .agentic_workflow import chat_store_private, ChatMessage, MessageRole
329
+ except ImportError:
330
+ from Agent.agentic_workflow import chat_store_private, ChatMessage, MessageRole
331
+ # Create minimal messages
332
+ user_msg = ChatMessage(role=MessageRole.USER, content=f"Uploaded document {doc_id}")
333
+ assistant_msg = ChatMessage(role=MessageRole.ASSISTANT, content=f"OCR stored: {ocr_text[:400]}")
334
+ chat_store_private.add_message(key="conversation", message=user_msg)
335
+ chat_store_private.add_message(key="conversation", message=assistant_msg)
336
+ chat_store_private.persist(str("chat_store/chat_store_private.json"))
337
+ except Exception:
338
+ pass
339
+
340
+ # Return doc id and small preview
341
+ preview = ocr_text[:400]
342
+ image_url = path
343
+ return UploadResp(doc_id=doc_id, text_preview=preview, image_url=image_url)
344
+
345
+
346
+ # ---------------------------------------------------------------------------
347
+ # Schema profile endpoints — dynamic multi-database support
348
+ # ---------------------------------------------------------------------------
349
+
350
+ @app.get("/schemas")
351
+ async def schemas_list():
352
+ return {"profiles": profile_registry.list(), "active_id": profile_registry.active_id}
353
+
354
+
355
+ @app.post("/schemas/add")
356
+ async def schemas_add_json(req: AddSchemaJsonReq):
357
+ """Register a database via connection URL (postgres/mysql/sqlite)."""
358
+ global agent
359
+ name = (req.name or "").strip()[:80]
360
+ if not name or not req.connection_url:
361
+ raise HTTPException(status_code=400, detail="name and connection_url are required")
362
+ entry = profile_registry.add(
363
+ name=name,
364
+ db_url=req.connection_url,
365
+ kind=_detect_demo_kind(name),
366
+ activate=bool(req.activate),
367
+ )
368
+ if bool(req.activate) and agent is not None:
369
+ try:
370
+ await agent.initialize_database(uri=req.connection_url)
371
+ except Exception as e:
372
+ raise HTTPException(status_code=400, detail=f"Profile saved, but DB init failed: {e}")
373
+ # Return full schema digest preview
374
+ return {"profile": entry, "schema": agent.ACTIVE_SCHEMA_PROFILE.summarize() if agent else None}
375
+
376
+
377
+ @app.post("/schemas/add-file")
378
+ async def schemas_add_file(file: UploadFile = File(...), name: Optional[str] = None, activate: bool = True):
379
+ """Register a database via file upload (.sqlite/.db/.sqlite3 or .csv)."""
380
+ global agent
381
+ fname = file.filename or "upload"
382
+ ext = os.path.splitext(fname)[-1].lower()
383
+ if ext not in SUPPORTED_DB_SUFFIXES:
384
+ raise HTTPException(
385
+ status_code=400,
386
+ detail=f"Unsupported file type '{ext}'. Supported: {sorted(SUPPORTED_DB_SUFFIXES)}",
387
+ )
388
+ display_name = (name or os.path.splitext(fname)[0]).strip()[:80] or "user_schema"
389
+
390
+ os.makedirs(SCHEMAS_DIR, exist_ok=True)
391
+
392
+ if ext == ".csv":
393
+ # Convert CSV into a single-table SQLite database
394
+ import pandas as pd
395
+ import tempfile
396
+
397
+ sqlite_path = os.path.join(SCHEMAS_DIR, f"{uuid.uuid4().hex}.db")
398
+ try:
399
+ contents = await file.read()
400
+ df = pd.read_csv(io.BytesIO(contents))
401
+ except Exception as e:
402
+ raise HTTPException(status_code=400, detail=f"CSV parse failed: {e}")
403
+ table_name = "".join(ch for ch in display_name if ch.isalnum() or ch == "_") or "data"
404
+ try:
405
+ engine_path = os.path.abspath(sqlite_path).replace("\\", "/")
406
+ df.to_sql(table_name, f"sqlite:///{engine_path}", index=False, if_exists="replace")
407
+ except Exception as e:
408
+ raise HTTPException(status_code=500, detail=f"CSV→SQLite conversion failed: {e}")
409
+ db_url = f"sqlite:///{engine_path}"
410
+ kind = "user"
411
+ else:
412
+ # Copy uploaded SQLite file into schemas dir
413
+ sqlite_path = os.path.join(SCHEMAS_DIR, f"{uuid.uuid4().hex}{ext}")
414
+ try:
415
+ contents = await file.read()
416
+ with open(sqlite_path, "wb") as fh:
417
+ fh.write(contents)
418
+ except Exception as e:
419
+ raise HTTPException(status_code=500, detail=f"Failed to save upload: {e}")
420
+ engine_path = sqlite_path.replace("\\", "/")
421
+ db_url = f"sqlite:///{engine_path}"
422
+ # Poke the file to validate it is really a SQLite database
423
+ try:
424
+ import sqlite3
425
+
426
+ conn = sqlite3.connect(sqlite_path)
427
+ tblset = {r[0] for r in conn.execute(
428
+ "SELECT name FROM sqlite_master WHERE type IN ('table','view')"
429
+ ).fetchall()}
430
+ conn.close()
431
+ except Exception as e:
432
+ raise HTTPException(status_code=400, detail=f"Invalid SQLite file: {e}")
433
+ kind = _detect_demo_kind(display_name, tblset)
434
+
435
+ entry = profile_registry.add(name=display_name, db_url=db_url, kind=kind, activate=activate)
436
+ if activate and agent is not None:
437
+ try:
438
+ await agent.initialize_database(uri=db_url)
439
+ except Exception as e:
440
+ raise HTTPException(status_code=400, detail=f"Profile saved, but DB init failed: {e}")
441
+ return {"profile": entry, "schema": agent.ACTIVE_SCHEMA_PROFILE.summarize() if agent else None}
442
+
443
+
444
+ @app.post("/schemas/switch/{profile_id}")
445
+ async def schemas_switch(profile_id: str):
446
+ """Switch the active database profile and re-initialize the agent against it."""
447
+ global agent
448
+ if agent is None:
449
+ raise HTTPException(status_code=503, detail="Agent not initialized")
450
+ entry = profile_registry.switch(profile_id)
451
+ if not entry:
452
+ raise HTTPException(status_code=404, detail="Profile not found")
453
+ # Dispose previous async engine best-effort
454
+ try:
455
+ if getattr(agent, "async_engine", None) is not None:
456
+ await agent.async_engine.dispose()
457
+ except Exception:
458
+ pass
459
+ try:
460
+ await agent.initialize_database(uri=entry["db_url"])
461
+ except Exception as e:
462
+ raise HTTPException(status_code=400, detail=f"Switch failed: {e}")
463
+ return {"profile": entry, "schema": agent.ACTIVE_SCHEMA_PROFILE.summarize()}
464
+
465
+
466
+ @app.delete("/schemas/{profile_id}")
467
+ async def schemas_delete(profile_id: str):
468
+ entry = profile_registry.get(profile_id)
469
+ if not entry:
470
+ raise HTTPException(status_code=404, detail="Profile not found")
471
+ # Remove uploaded backing file for file-based profiles
472
+ db_url = entry.get("db_url") or ""
473
+ try:
474
+ if db_url.startswith("sqlite:///"):
475
+ p = db_url.replace("sqlite:///", "", 1)
476
+ if os.path.exists(p) and str(SCHEMAS_DIR) in p:
477
+ os.remove(p)
478
+ except Exception:
479
+ pass
480
+ profile_registry.remove(profile_id)
481
+ return {"deleted": profile_id}
482
+
483
+
484
+ @app.get("/schema/current")
485
+ async def schema_current():
486
+ """Current active schema summary (tables/columns/samples) for the UI."""
487
+ global agent
488
+ if agent is None:
489
+ raise HTTPException(status_code=503, detail="Agent not initialized")
490
+ return agent.ACTIVE_SCHEMA_PROFILE.summarize()
491
+
492
+ if __name__ == '__main__':
493
+ port = int(os.environ.get("WORKER_PORT", 8700))
494
+ uvicorn.run(app, host="127.0.0.1", port=port)
Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ☁️ Dockerfile for Hugging Face Spaces — Cloud-Only (Lightweight)
2
+ # Image size: ~500MB (no Ollama, no local models)
3
+ # All LLM inference is handled by Groq API and HF Inference API via USE_HF_CLOUD=1
4
+ FROM python:3.11-slim
5
+
6
+ # Prevent Python from writing pyc files and buffering stdout/stderr
7
+ ENV PYTHONDONTWRITEBYTECODE=1
8
+ ENV PYTHONUNBUFFERED=1
9
+
10
+ # Cloud mode: all LLM calls go to Groq / HF Inference — no local Ollama needed
11
+ ENV USE_HF_CLOUD=1
12
+
13
+ # Install system dependencies (Tesseract for OCR fallback only)
14
+ RUN apt-get update && apt-get install -y \
15
+ curl \
16
+ zstd \
17
+ tesseract-ocr \
18
+ libtesseract-dev \
19
+ gcc \
20
+ libpq-dev \
21
+ && rm -rf /var/lib/apt/lists/*
22
+
23
+ WORKDIR /app
24
+
25
+ # Install Python dependencies
26
+ COPY requirements.txt .
27
+ RUN pip install --no-cache-dir --upgrade pip && \
28
+ pip install --no-cache-dir -r requirements.txt && \
29
+ pip install --no-cache-dir llama-index-llms-huggingface-api huggingface_hub
30
+
31
+ # Copy application code
32
+ COPY . .
33
+
34
+ # Hugging Face Spaces requires port 7860
35
+ EXPOSE 7860
36
+
37
+ # Fix line endings and permissions on startup script
38
+ RUN sed -i 's/\r$//' start_hf.sh && chmod +x start_hf.sh
39
+ RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app 2>/dev/null || true
40
+ USER appuser
41
+
42
+ CMD ["./start_hf.sh"]
README.md CHANGED
@@ -1,13 +1,633 @@
1
  ---
2
- title: QueryLensV2
3
- emoji: ⚡
4
  colorFrom: blue
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 6.30.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: QueryLens V2
3
+ emoji: 🔍
4
  colorFrom: blue
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 5.0.0
 
8
  app_file: app.py
9
  pinned: false
10
  ---
11
 
12
+
13
+ # 🤖 Agentic Text2SQL & Document VQA
14
+ Multi-Agent System
15
+
16
+ ![Architecture](https://img.shields.io/badge/Architecture-Multi--Agent-blue)
17
+ ![Database](https://img.shields.io/badge/Database-Agnostic-success)
18
+ ![LLM](https://img.shields.io/badge/LLMs-Qwen%20%7C%20Ollama-orange)
19
+ ![Protocol](https://img.shields.io/badge/Protocol-MCP-purple)
20
+
21
+ An advanced, hardware-optimized AI pipeline built on a multi-agent orchestration architecture. This system seamlessly integrates natural language Text-to-SQL generation with a Vision-Language Model (VLM) for Optical Character Recognition (OCR) and Visual Question Answering (VQA).
22
+
23
+ By leveraging the Model Context Protocol (MCP), local LLMs via Ollama, and intelligent memory management, this project achieves production-grade data extraction and database querying running entirely on local hardware within tight memory constraints.
24
+
25
+ ---
26
+
27
+ ## Key Features
28
+
29
+ - **Multi-Agent Orchestration:** A dynamic routing system featuring specialized agents — MemoryAgent, QueryCraftAgent, and ResultPresenterAgent — each with a clearly defined role in the pipeline.
30
+ - **Dynamic Database Profiles:** Connect any database by connection string, or upload a `.sqlite`/`.db`/`.csv` file directly from the UI. Profiles are registered, switchable, and deletable at runtime via the `Database` panel or the `/api/schemas` REST surface — the built-in employee sample DB ships as one profile (`demo_employee`) among many.
31
+ - **Schema-Aware Generic Agents:** The agent pipeline reads a live introspected schema profile (tables, columns, PK/FK, row counts, sample rows) instead of assuming a fixed schema. The fourteen employee-specific `fast_sql` templates activate only when the employee demo is the active profile; every other database gets generic `schema.list_tables / schema.describe_table / schema.sample_data / sql.build_select` MCP tools and profile-aware prompts, validators, and reducers.
32
+ - **Interactive Charts:** Query results that visualize well (category breakdowns, comparisons, time series) are detected automatically and rendered as ECharts visualizations — pie, bar, or line — in a sepia-toned palette. Chart specs ride in the query response as a first-class `chart` field; detection is conservative and never corrupts a textual answer.
33
+ - **Modern Sepia UI:** A Claude-inspired coffee/sepia interface with serif headings and a warm terracotta accent, wrapping the multi-agent trace panels (Memory / QueryCraft / ResultPresenter), live schema browsing, and charting.
34
+ - **Vision-Language Question Answering:** VQA/OCR extraction from invoices and unstructured documents. Served locally via Ollama (`qwen2-vl:2b`) or — in cloud mode — through Groq's `qwen/qwen3.8-27b` vision model (free tier).
35
+ - **Three-Level Text-to-SQL Engine:** Translates natural language questions into syntactically valid SQL through a progressive reasoning architecture, with automatic self-correction at each escalation level.
36
+ - **Semantic Gatekeeping:** A multi-layer validation pipeline filters hallucinated SQL, undefined aliases, missing joins, and incorrect aggregation patterns before any query reaches the database.
37
+ - **Dynamic VRAM Orchestration:** Custom memory management algorithms automatically load and unload models from GPU VRAM to prevent out-of-memory crashes, enabling concurrent AI workloads on consumer hardware.
38
+ - **Unified MCP Integration:** All external data sources — relational databases and vision models alike — are accessed through a single, uniform Model Context Protocol interface.
39
+ - **Database Agnostic Design:** Architected to interface with PostgreSQL, MySQL, SQLite, MS SQL Server, and Oracle via SQLAlchemy.
40
+ - **Conversational Interface:** A full Web UI supporting natural language interaction with persistent session context.
41
+
42
+ ---
43
+
44
+ ## Dynamic Databases & Visual Analytics
45
+
46
+ ### Database profiles
47
+
48
+ Any database the worker can reach via SQLAlchemy becomes a first-class profile:
49
+
50
+ | Endpoint | Method | Purpose |
51
+ |---|---|---|
52
+ | `/api/schemas` | GET | List registered profiles + active id |
53
+ | `/api/schemas/add` | POST | Register via `name` + `connection_url` (postgres/mysql/sqlite) |
54
+ | `/api/schemas/add-file` | POST | Upload `.sqlite`/`.db` (used as-is) or `.csv` (converted to a single-table SQLite DB) |
55
+ | `/api/schemas/switch/{id}` | POST | Activate a profile and re-initialize the agent against it |
56
+ | `/api/schemas/{id}` | DELETE | Remove a profile (+ its uploaded backing file) |
57
+ | `/api/schema/current` | GET | Live summary of the active schema (tables, columns, row counts, sample rows) |
58
+
59
+ Profiles persist in `chat_store/schema_profiles.json` and survive restarts; uploaded files are stored under `uploads/schemas/`. On startup, the worker auto-registers the `DB_CONNECTION_URL` database as the initial active profile.
60
+
61
+ ### Chart contract
62
+
63
+ When a query returns rows that visualize well, the ResultPresenter embeds a chart spec (pie/bar/line, labels + numeric series) that the worker exposes as `{"chart": {...}}` alongside the text `answer`. Selection heuristics: date-like first column + numeric series → line; ≤8 categories with a single numeric series → pie; otherwise bar. Detection caps at 60 points and never mutates the answer text.
64
+
65
+ ### Working against the demo employee database
66
+
67
+ The built-in employee sample (MySQL/PostgreSQL containers in `docker-compose.yml`, or the `demo_employee` profile) keeps all battle-tested heuristics: `to_date = '9999-01-01'` current-row filters, the manager/department join knowledge, the 14 `fast_sql` MCP templates, and the invariant enforcement layer.
68
+
69
+ ---
70
+
71
+ ## System Architecture and Agentic Workflow
72
+
73
+ The project employs a decoupled, asynchronous microservices architecture. The Web UI communicates with a backend worker, which orchestrates all agent requests through the Model Context Protocol.
74
+
75
+ ### The Three-Agent Pipeline
76
+
77
+ **1. MemoryAgent**
78
+
79
+ The MemoryAgent acts as the entry point for all user queries. It performs three functions before any SQL generation occurs: checking whether the current query can be satisfied from historical conversation context, rephrasing ambiguous or under-specified queries based on prior interactions, and routing validated new queries to the appropriate downstream agent. This layer prevents redundant computation and improves response latency for repeated or related questions.
80
+
81
+ **2. QueryCraftAgent — The Three-Level Text-to-SQL Engine**
82
+
83
+ The QueryCraftAgent is the core reasoning engine of the system. It implements a progressive escalation architecture that balances inference speed with accuracy:
84
+
85
+ - **Level 1 — Pure LLM Intelligence:** Zero-shot semantic translation of natural language to SQL using Qwen 2.5 Coder. The generated query passes through a semantic validation pipeline that checks alias correctness, required table joins, aggregation integrity, and department or entity filters before being accepted.
86
+
87
+ - **Level 2 — LLM with SQL Fixer:** When Level 1 fails validation, the agent enters an autonomous self-correction loop. The SQL Fixer applies a deterministic set of targeted transformations — normalizing aliases, injecting missing to_date filters, repairing phantom column references, and enforcing PostgreSQL-compliant GROUP BY clauses — before re-validating the output.
88
+
89
+ - **Level 3 — LLM with MCP Schema-Grounded SQL Generation:** The deepest reasoning level, reserved for queries that fail both prior levels. For the built-in employee demo, the agent calls one of fourteen registered `fast_sql` MCP tools, each of which queries the live database schema via SQLAlchemy's inspector to retrieve actual column names and table structures, then programmatically constructs a valid SQL template grounded in the real schema. For any user-registered database, the agent instead grounds itself through the generic `schema.list_tables` / `schema.describe_table` / `schema.sample_data` MCP tools, producing a verified live-schema + sample-data hint that applies to any database. In both cases the template is passed as a verified hint to the LLM, which refines it before the Fixer loop runs. Because the hint is built from the actual schema rather than the LLM's training data, this level eliminates the class of failures caused by hallucinated column names or missing joins.
90
+
91
+ **3. ResultPresenterAgent**
92
+
93
+ The ResultPresenterAgent executes the validated SQL query against the target database, translates raw result sets into natural conversational responses, handles execution errors and edge cases, and persists the interaction to the conversation history for future MemoryAgent lookups.
94
+
95
+ ### Multi-Agent Orchestration Flow
96
+
97
+ ```mermaid
98
+ graph TD
99
+ User([User]) --> Web["Web Application\nPort 8000"]
100
+
101
+ Web -->|Image Upload| Worker["Backend Worker\nPort 8700"]
102
+ Web -->|Text Query| Worker
103
+
104
+ subgraph MCP["MCP Tool Server — Port 8701"]
105
+ DocScan["document_scanner.process\nTesseract OCR"]
106
+ FastSQL["fast_sql tools\nSchema-Grounded SQL Generation"]
107
+ VisionQA["granite_vision.qa\nQwen 3.5 2B Vision"]
108
+ end
109
+
110
+ Worker -->|"Upload: MCP tool call"| DocScan
111
+ DocScan -->|"doc_id + OCR text + image path"| Store[("Document Store\nchat_store/docs/")]
112
+
113
+ Worker -->|"OCR Q&A mode\ndoc_id present"| VisionQA
114
+ Store -->|image path| VisionQA
115
+ VisionQA --> OllamaV(["Ollama\nQwen 3.5 2B Vision"])
116
+ OllamaV --> Presenter
117
+
118
+ Worker -->|Text Query| Memory["MemoryAgent"]
119
+ Memory -->|Cached answer| Presenter["ResultPresenterAgent"]
120
+ Memory -->|New query| QCAgent["QueryCraftAgent"]
121
+
122
+ QCAgent -->|"Level 1 and 2\nDirect Ollama call"| OllamaSQL(["Ollama\nQwen 2.5 Coder"])
123
+ QCAgent -->|"Level 3\nMCP tool call"| FastSQL
124
+ FastSQL -->|"Schema-validated SQL hint"| OllamaSQL
125
+ OllamaSQL -->|Raw SQL| Fixer["SQL Fixer +\nSemantic Validator"]
126
+ Fixer -->|"Validated SQL\nvia SQLAlchemy"| DB[("PostgreSQL / MySQL")]
127
+
128
+ DB --> Presenter
129
+ Presenter -->|Persist to history| Memory
130
+ Presenter --> Answer(["Natural Language Answer"])
131
+ ```
132
+
133
+ ---
134
+
135
+ ## Infrastructure and Deployment Architecture
136
+
137
+ ### Containerized Microservices
138
+
139
+ The system is implemented as a Dockerized microservices architecture, with each component running as an isolated, independently deployable service. Docker Compose orchestrates three services: the main application and agent worker, the MCP tool server, and the relational databases (PostgreSQL and MySQL). Database containers are provisioned with health checks using `pg_isready` and `mysqladmin ping`, and the application container is configured with `condition: service_healthy` dependencies to eliminate the startup race condition inherent in naive `depends_on` configurations.
140
+
141
+ ### Native-Bridge Hybrid Offloading
142
+
143
+ For peak inference performance, the system uses a hybrid offloading strategy. The application logic and MCP servers run inside Docker containers for portability and isolation, while Ollama and all GPU inference are offloaded to the native Windows host and accessed by the containers over the WSL2 host bridge network (`OLLAMA_BASE_URL=http://<wsl2-host-ip>:11434`).
144
+
145
+ This architecture eliminates the virtualization overhead introduced by Docker Desktop's Linux VM layer. By giving the inference engine direct access to NVIDIA CUDA cores and the full system memory pool — rather than a virtualized slice — the 1.5B parameter model achieves response times measured in seconds rather than minutes. The separation also means that GPU memory pressure from Ollama does not compete with the container's allocated memory ceiling.
146
+
147
+ ### Database Health and Startup Reliability
148
+
149
+ A production-grade startup sequence is enforced through Docker health checks and application-level retry logic. The agent application implements a ten-attempt retry loop with five-second intervals on initialization, including a `SELECT 1` connection verification before the schema is read. This ensures consistent behavior across restarts and eliminates the class of intermittent failures caused by the application reading an empty or partially initialized schema during database startup.
150
+
151
+ ### MCP Tool Server Architecture
152
+
153
+ The Model Context Protocol server runs as a dedicated microservice on port 8701. Three categories of tools are registered at startup:
154
+
155
+ **document_scanner.process** handles Tesseract OCR and is called at image upload time, not at query time. It returns a doc_id, the extracted text, and triggers persistence of both the OCR output and the image path to the document store.
156
+
157
+ **granite_vision.qa** is the direct visual question-answering tool backed by Qwen 3.5 2B Vision via Ollama. It is called when a user submits a question with a doc_id and the original image file is available on disk. The internal tool identifier `granite_vision.qa` was retained from the original design specification; the underlying model was later replaced with Qwen 3.5 2B Vision for improved OCR accuracy and reduced VRAM usage, with no changes required to the agent orchestration code.
158
+
159
+ **fast_sql tools** are fourteen schema-grounded SQL generation tools used exclusively at Level 3 of the QueryCraftAgent. Each tool queries the live database schema via SQLAlchemy's inspector to retrieve actual column names, then uses a deterministic `_build_sql()` function to construct a valid query, optionally verified by a short LLM call. The result is returned as a schema-validated SQL hint to the QueryCraftAgent, which passes it to the LLM for final refinement. This design means Level 3 failures are caused by query complexity or intent ambiguity, never by hallucinated schema details.
160
+
161
+ ---
162
+
163
+ ## Unified Multimodal Integration via MCP
164
+
165
+ A defining architectural feature of this system is that OCR and multimodal reasoning are integrated through the same Model Context Protocol used for database access. The Qwen 3.5 2B Vision model is registered as a named MCP tool: `granite_vision.qa`. This internal tool identifier was retained from the original design specification; the underlying engine was subsequently replaced with Qwen 3.5 2B Vision, which demonstrated superior OCR accuracy and a smaller VRAM footprint. Because the tool interface is decoupled from its implementation, this substitution required no changes to the agent orchestration code — only the MCP tool registration was updated.
166
+
167
+ This design delivers three concrete engineering properties:
168
+
169
+ **Uniform Protocol:** The orchestrator issues identical-format tool calls regardless of whether the data source is a SQL table or a visual document. There are no special-case code paths for different modalities.
170
+
171
+ **Modular Replaceability:** The vision model is encapsulated behind its MCP interface. Upgrading to a different vision model — such as a GPT-4V endpoint — requires updating only the tool registration, not any agent logic.
172
+
173
+ **Cross-Modal Reasoning Capability:** Because both data sources share the same protocol, the agent can compose multi-step reasoning across modalities. For example, the system can extract a value from a document via the vision tool and immediately verify it against a database record via the SQL tool, within a single agentic workflow.
174
+
175
+ ```text
176
+ Multimodal Request Flow
177
+
178
+ Worker receives query with image path
179
+ |
180
+ +-- Image detected --> ocr_agent_qa()
181
+ |
182
+ +-- Unload Qwen 2.5 Coder (free VRAM)
183
+ |
184
+ +-- MCP tool call: granite_vision.qa
185
+ |
186
+ MCP Server (port 8701)
187
+ |
188
+ Qwen 3.5 2B Vision (Ollama)
189
+ |
190
+ Structured answer returned
191
+ |
192
+ +-- No image --> Standard Text-to-SQL pipeline (unchanged)
193
+ ```
194
+
195
+ ---
196
+
197
+ ## SQL Validation Pipeline
198
+
199
+ The semantic validation layer is one of the most technically substantive components of the system. Rather than trusting LLM output directly, every generated SQL query passes through a deterministic validation pipeline before execution. Key checks include:
200
+
201
+ - **Alias Integrity:** All table aliases used in SELECT, WHERE, JOIN, and GROUP BY clauses must be defined in FROM or JOIN declarations. The validator maintains a set of defined and used aliases and rejects queries with undefined references.
202
+ - **Salary Table Recognition:** The `salary` table name was explicitly excluded from the SQL keyword blocklist, as it is both a legitimate table name and a column name in the employee schema. Incorrect inclusion in the keyword set caused the validator to silently discard valid salary table joins.
203
+ - **Department Filter Enforcement:** Queries that reference a specific department by name are validated to confirm that a corresponding WHERE filter exists in the generated SQL. This prevents queries that return all departments when the user asked for one.
204
+ - **PostgreSQL GROUP BY Compliance:** Queries containing aggregate functions are checked to ensure all non-aggregated SELECT columns appear in the GROUP BY clause, enforcing strict PostgreSQL semantics.
205
+ - **Manager Schema Awareness:** Queries involving manager data are validated to confirm use of the `dept_manager` table rather than `dept_emp`. The validation produces a warning rather than a hard rejection, allowing the downstream semantic adjuster to regenerate the correct SQL before the query reaches the database.
206
+
207
+ ---
208
+
209
+ ## Research Methodology: Fine-Tuning and Model Selection
210
+
211
+ As part of the project's scientific evaluation, a custom model fine-tuning pipeline was developed and benchmarked against the selected production model.
212
+
213
+ **LoRA Fine-Tuning:** The base Qwen 2.5 3B model was fine-tuned using Low-Rank Adaptation on a specialized Text-to-SQL dataset.
214
+
215
+ **Weight Merging:** The LoRA adapters were merged back into the base model weights via `merge_qwen_to_ollama.py` and quantized for local deployment via Ollama.
216
+
217
+ **Comparative Evaluation:** The fine-tuned general model was benchmarked against the zero-shot `qwen2.5-coder:1.5b`, which is pre-trained on a large corpus of code and SQL.
218
+
219
+ **Engineering Decision:** The benchmark results showed that the Coder model's zero-shot SQL accuracy exceeded that of the general LoRA fine-tune, with faster inference and lower error rates on complex multi-table joins. The production architecture was updated accordingly. This outcome demonstrates a data-driven engineering decision: fine-tuning is not always the optimal path when a domain-specialized pretrained model exists for the target task.
220
+
221
+ See `Fine_Tuning_Qwen_2_5_3B.ipynb` and the `merged_qwen2_5_3b_text2sql` directory for the complete fine-tuning methodology and benchmark results.
222
+
223
+ ---
224
+
225
+ ## Technology Stack
226
+
227
+ | Component | Technology |
228
+ |---|---|
229
+ | Core Framework | Python 3.11+, FastAPI, Uvicorn |
230
+ | AI Orchestration | LlamaIndex, Model Context Protocol (MCP) |
231
+ | Local Inference | Ollama (C++ optimized, memory-mapped) |
232
+ | Text-to-SQL Model | qwen2.5-coder:1.5b |
233
+ | Vision/OCR Model | qwen3.5:2b (registered as granite_vision.qa) |
234
+ | Database ORM | SQLAlchemy |
235
+ | Containerization | Docker, Docker Compose |
236
+ | Databases | PostgreSQL, MySQL |
237
+
238
+ ---
239
+
240
+ ## Installation and Setup
241
+
242
+ ### Prerequisites
243
+
244
+ - Ollama installed and running on the host machine
245
+ - Python 3.11 or higher
246
+ - Docker and Docker Compose
247
+ - A supported database (PostgreSQL or MySQL)
248
+
249
+ ### 1. Pull Required Models
250
+
251
+ ```bash
252
+ ollama pull qwen2.5-coder:1.5b
253
+ ollama pull qwen3.5:2b
254
+ ```
255
+
256
+ ### 2. Configure Environment
257
+
258
+ Install Python dependencies:
259
+
260
+ ```bash
261
+ pip install -r requirements.txt
262
+ ```
263
+
264
+ Create a `.env` file in the `Agent/` directory (see `.env.example` for the full reference).
265
+
266
+ **Recommended (cloud-only, no local models needed):** use the same HF Inference API configuration as the Hugging Face Spaces deployment:
267
+
268
+ ```env
269
+ DB_CONNECTION_URL=postgresql://user:password@localhost:5432/dbname
270
+ USE_HF_CLOUD=1
271
+ HF_API_TOKEN=hf_xxx
272
+ HF_LLM_MODEL=Qwen/Qwen2.5-Coder-7B-Instruct
273
+
274
+ # Cloud VQA via Groq (free tier)
275
+ GROQ_API_KEY=gsk_xxx
276
+ GROQ_VISION_MODEL=qwen/qwen3.8-27b
277
+ ```
278
+
279
+ **Local Ollama (optional):** with `USE_HF_CLOUD=0`, the configured Ollama model is used — and if it is not installed while `HF_API_TOKEN` is present, the worker **auto-falls back** to HF Inference (`HF_LLM_MODEL`) instead of failing with 404 handshakes.
280
+
281
+ ### 3. Run Without Docker
282
+
283
+ Start each microservice in a separate terminal:
284
+
285
+ ```bash
286
+ # Terminal 1 — Backend Worker
287
+ python -u -m uvicorn "Agent.worker:app" --port 8700
288
+
289
+ # Terminal 2 — MCP Tool Server
290
+ python -m uvicorn "Agent.mcp_server:app" --port 8701
291
+
292
+ # Terminal 3 — Web UI
293
+ python -m uvicorn "web.app:app" --port 8000
294
+ ```
295
+
296
+ Navigate to `http://localhost:8000` to interact with the system. Use the **Database** panel to connect your own database (connection URL or `.sqlite`/`.csv` upload) — the built-in employee sample is provided as a container-backed profile.
297
+
298
+ ### 4. Run With Docker
299
+
300
+ Update `OLLAMA_BASE_URL` in `docker-compose.yml` to point to your host machine's Ollama instance, then run:
301
+
302
+ ```bash
303
+ docker-compose up --build demo-agent-app
304
+ ```
305
+
306
+ The database containers include health checks and will be fully initialized before the application starts.
307
+
308
+ ---
309
+
310
+ ## Deployment on HuggingFace Spaces
311
+
312
+ ### Quick Deploy (current, cloud-only)
313
+
314
+ The app is fully cloud-based (`USE_HF_CLOUD=1`): Text-to-SQL runs on HF Inference
315
+ (`Qwen/Qwen2.5-Coder-7B-Instruct`), VQA on Groq (`qwen/qwen3.8-27b`), and the
316
+ built-in `demo_employee` SQLite profile ships with the repo — no external DB
317
+ service is needed on Spaces.
318
+
319
+ > **Note:** HF Spaces moved the **Docker SDK to a paid tier** (free CPU 2026).
320
+ > Deploy there with the free **Gradio SDK** instead — `app.py` at the repo root
321
+ > spawns the same three services the Docker image ran (worker `:8700`,
322
+ > MCP `:8701`, sepia web UI `:7860`) and mounts a minimal Gradio anchor page at
323
+ > `/gradio-lp`. The UI at `/` is unchanged.
324
+
325
+ 1. **Create the Space** — huggingface.co → *New Space* → SDK: **Gradio** →
326
+ blank template → name it (e.g. `querylens`). Hardware: free CPU basic.
327
+ 2. **Push the project files** into the Space repo. Easiest on Windows is the
328
+ bundled helper:
329
+ ```powershell
330
+ .\deploy_space.ps1 -SpaceName querylens
331
+ ```
332
+ It clones `huggingface.co/spaces/<you>/<name>`, copies the project across
333
+ (respecting the exclusions: no `.env`, no `chat_store/`, no 350 MB
334
+ `dataset_full` dumps, no `__pycache__`), merges the HF frontmatter into the
335
+ Space `README.md` (keeping the generated `sdk_version`), commits and pushes.
336
+ 3. **Add Secrets** (Space settings → Variables and Secrets — never commit them):
337
+ | Secret | Purpose |
338
+ |---|---|
339
+ | `HF_API_TOKEN` | HF Inference API — Text-to-SQL (`Qwen/Qwen2.5-Coder-7B-Instruct`) |
340
+ | `GROQ_API_KEY` | Groq vision VQA (`qwen/qwen3.8-27b`, free tier) |
341
+ No `DB_CONNECTION_URL` is required — the worker auto-activates the bundled demo.
342
+ Optional: set `DB_CONNECTION_URL` to a hosted Postgres (e.g. Neon) for a real
343
+ external database.
344
+ 4. **Open the Space** — the sepia UI loads with the demo profile active.
345
+ The **Database** panel lets you register additional databases (hosted
346
+ Postgres/MySQL URLs, or uploaded `.sqlite`/`.csv` files) at runtime.
347
+
348
+ **Local Docker runs still work** for your own machine: `docker build` +
349
+ `docker-compose.yml` are unchanged and `start_hf.sh` serves the identical
350
+ stack — only the Spaces *hosting* path is now the Gradio launcher.
351
+
352
+ Note: free Spaces sleep after inactivity (cold start ~1–2 min). Uploaded schema
353
+ files and chat history are ephemeral unless you enable *Persistent Storage* in
354
+ the Space settings.
355
+
356
+ ### Historical deployment journey (reference)
357
+
358
+ This section documents the **complete deployment journey** — from the first proof-of-concept tunnel approach to the final production-ready hybrid architecture. Each phase is explained with commands and rationale so this can serve as a reference for deploying any multi-modal AI application on HuggingFace Spaces.
359
+
360
+ ---
361
+
362
+ ### Understanding HuggingFace Spaces Constraints
363
+
364
+ Before choosing a deployment strategy, it is essential to understand what the free tier of HuggingFace Spaces provides and restricts:
365
+
366
+ | Resource | Free Tier |
367
+ |----------|-----------|
368
+ | CPU | 2 vCPUs |
369
+ | RAM | 16 GB |
370
+ | GPU | None |
371
+ | Storage | Ephemeral (wiped on restart) |
372
+ | Public port | 7860 only |
373
+ | Timeout | Space sleeps after inactivity |
374
+
375
+ The key challenge: **running a local LLM (e.g. `qwen2.5-coder:1.5b`) via Ollama consumes ~1.5–3 GB RAM, leaving limited headroom for vision models and the application stack.** Running a vision-language model such as `qwen3.5:2b` (~3 GB) alongside the text model causes out-of-memory (OOM) failures on the free CPU tier.
376
+
377
+ ---
378
+
379
+ ### Phase 1 — Cloudflare Tunnel: Bridging Local Resources to the Cloud
380
+
381
+ #### Theory
382
+
383
+ The simplest approach to deploy a resource-intensive app on HF Spaces is to **not run the heavy models in the cloud at all**. Instead, you run the LLM and VLM locally on your development machine and expose the Ollama API endpoint to the internet via a secure tunnel. The HF Space container merely hosts the web frontend and proxies inference requests back to your local machine.
384
+
385
+ This approach has zero cloud compute cost and allows full GPU acceleration locally. However, it requires your development machine to remain **online and running at all times**, making it unsuitable for a persistent public demo.
386
+
387
+ #### Setup
388
+
389
+ **Step 1: Install Cloudflared on your local machine**
390
+ ```bash
391
+ # Windows (via winget)
392
+ winget install Cloudflare.cloudflared
393
+
394
+ # Or download directly
395
+ # https://github.com/cloudflare/cloudflared/releases
396
+ ```
397
+
398
+ **Step 2: Start Ollama locally**
399
+ ```bash
400
+ ollama serve
401
+ # Ollama now listens on http://localhost:11434
402
+ ```
403
+
404
+ **Step 3: Create a public tunnel to your local Ollama port**
405
+ ```bash
406
+ cloudflared tunnel --url http://localhost:11434
407
+ ```
408
+
409
+ Cloudflared will print a public HTTPS URL like:
410
+ ```
411
+ https://your-random-id.trycloudflare.com
412
+ ```
413
+
414
+ **Step 4: Set the tunnel URL as a secret in your HF Space**
415
+
416
+ In the HF Space settings under **Variables and Secrets**, add:
417
+ ```
418
+ OLLAMA_BASE_URL = https://your-random-id.trycloudflare.com
419
+ ```
420
+
421
+ The application code reads `OLLAMA_BASE_URL` and routes all inference calls through the tunnel to your local GPU.
422
+
423
+ #### Limitation
424
+
425
+ - The tunnel URL changes every time `cloudflared` restarts, requiring a secret update.
426
+ - Requires a continuously running local machine.
427
+ - Not viable for a shared capstone demo or public deployment.
428
+
429
+ ---
430
+
431
+ ### Phase 2 — Self-Contained Docker: Running Ollama Inside the Container
432
+
433
+ #### Theory
434
+
435
+ The next evolution is to **embed Ollama directly into the Docker image** and pull models at container startup. This makes the deployment fully self-contained — no external machine is needed. The HF Space container becomes a complete inference server.
436
+
437
+ The challenge is that HF Spaces rebuilds the Docker image on every push but does **not cache downloaded model weights** between restarts (storage is ephemeral). This means every **Factory Reboot** triggers a fresh ~1–3 GB model download, causing a cold-start delay of 2–5 minutes.
438
+
439
+ To prevent HF's health monitor from timing out the Space during this download, model pulling is performed **asynchronously in the background**, allowing the web UI to become responsive immediately while the model fetches in parallel.
440
+
441
+ #### Dockerfile Changes
442
+
443
+ Add Ollama installation to the `Dockerfile`:
444
+
445
+ ```dockerfile
446
+ # Install Ollama binary (pinned to a stable release)
447
+ RUN curl -L https://github.com/ollama/ollama/releases/download/v0.5.11/ollama-linux-amd64.tgz \
448
+ -o ollama.tgz && \
449
+ tar -C /usr -xzf ollama.tgz && \
450
+ rm ollama.tgz
451
+ ```
452
+
453
+ #### Startup Script (`start_hf.sh`)
454
+
455
+ ```bash
456
+ #!/bin/bash
457
+ export HOME=/root
458
+
459
+ echo "[HF-INIT] Starting Ollama server..."
460
+ ollama serve &
461
+ OLLAMA_PID=$!
462
+
463
+ # Wait for Ollama to become healthy (up to 20 attempts)
464
+ for i in $(seq 1 20); do
465
+ if curl -sf http://localhost:11434/api/tags > /dev/null 2>&1; then
466
+ echo "[HF-INIT] Ollama is ALIVE!"
467
+ break
468
+ fi
469
+ echo "[HF-INIT] Waiting... ($i/20)"
470
+ sleep 3
471
+ done
472
+
473
+ # Pull the text model asynchronously (non-blocking)
474
+ echo "[HF-INIT] Pulling qwen2.5-coder:1.5b in background..."
475
+ ollama pull qwen2.5-coder:1.5b &
476
+
477
+ # Start application services immediately (do not wait for model pull)
478
+ echo "[HF-INIT] Starting Backend Worker..."
479
+ python -m uvicorn Agent.worker:app --host 0.0.0.0 --port 8700 &
480
+
481
+ echo "[HF-INIT] Starting MCP Tool Server..."
482
+ python -m uvicorn Agent.mcp_server:app --host 0.0.0.0 --port 8701 &
483
+
484
+ echo "[HF-INIT] Starting Web UI on port 7860..."
485
+ exec python -m uvicorn web.app:app --host 0.0.0.0 --port 7860
486
+ ```
487
+
488
+ The `&` (ampersand) operator sends the model pull to the background. The `exec` on the last line replaces the shell process with the web server, ensuring HF's process monitor tracks the correct PID.
489
+
490
+ #### Limitation
491
+
492
+ - **Vision model OOM**: Adding `qwen3.5:2b` alongside `qwen2.5-coder:1.5b` exceeds the 16 GB RAM limit when both are loaded simultaneously.
493
+ - Model weights are re-downloaded on every Factory Reboot.
494
+ - Ollama version pinning is critical — newer models require newer Ollama binaries and pulling the wrong combination causes `412` errors.
495
+
496
+ ---
497
+
498
+ ### Phase 3 — Hybrid Serverless API (Final Production Architecture)
499
+
500
+ #### Theory
501
+
502
+ The final and most robust architecture eliminates the in-container LLM entirely for text generation and uses **external serverless inference APIs** instead. The container only runs lightweight services (web UI, API proxy, Tesseract OCR), while all neural inference is delegated to dedicated providers:
503
+
504
+ | Task | Provider | Model | Cost |
505
+ |------|----------|-------|------|
506
+ | Text-to-SQL | HuggingFace Inference API | `Qwen/Qwen2.5-Coder-7B-Instruct` | Free tier |
507
+ | Vision Q&A | Groq API | `meta-llama/llama-4-scout-17b-16e-instruct` | Free (14,400 req/day) |
508
+ | OCR | Tesseract (in container) | — | Free |
509
+ | Database | Neon PostgreSQL | — | Free tier |
510
+
511
+ This eliminates OOM risk entirely, removes the model download cold-start, and makes the container startup under 30 seconds.
512
+
513
+ #### Why Groq for Vision Instead of HuggingFace Serverless?
514
+
515
+ HuggingFace's serverless inference for vision-language models has two limitations on the free tier:
516
+ 1. Most VLM models are not routed through any enabled provider for free-tier accounts.
517
+ 2. Google Gemini's free tier blocks requests originating from cloud datacenter IP ranges (such as HF's infrastructure), setting the effective quota to zero even for valid free-tier API keys.
518
+
519
+ **Groq** is purpose-built for API-first server deployments and explicitly allows free-tier requests from cloud IPs. It provides 14,400 free requests per day with no IP restrictions.
520
+
521
+ #### Required HuggingFace Space Secrets
522
+
523
+ Set these in **Space Settings → Variables and Secrets**:
524
+
525
+ ```
526
+ USE_HF_CLOUD = 1
527
+ HF_API_TOKEN = # HuggingFace access token
528
+ GROQ_API_KEY = # From console.groq.com (free)
529
+ DB_CONNECTION_URL = # Neon PostgreSQL connection string
530
+ ```
531
+
532
+ #### Obtaining API Keys
533
+
534
+ **HuggingFace Token:**
535
+ 1. Go to https://huggingface.co/settings/tokens
536
+ 2. Create a token with `read` scope (or `write` if you need to push models)
537
+
538
+ **Groq API Key:**
539
+ 1. Go to https://console.groq.com
540
+ 2. Sign in with Google / GitHub
541
+ 3. Navigate to **API Keys** → **Create API Key**
542
+ 4. Copy the key
543
+
544
+ **Neon PostgreSQL:**
545
+ 1. Go to https://neon.tech
546
+ 2. Create a free project
547
+ 3. Copy the connection string from the dashboard
548
+
549
+ #### Slim Dockerfile (No Ollama Required)
550
+
551
+ ```dockerfile
552
+ FROM python:3.11-slim
553
+
554
+ ENV PYTHONDONTWRITEBYTECODE=1
555
+ ENV PYTHONUNBUFFERED=1
556
+ ENV USE_HF_CLOUD=1
557
+
558
+ RUN apt-get update && apt-get install -y \
559
+ curl \
560
+ tesseract-ocr \
561
+ libtesseract-dev \
562
+ gcc \
563
+ libpq-dev \
564
+ && rm -rf /var/lib/apt/lists/*
565
+
566
+ WORKDIR /app
567
+ COPY requirements.txt .
568
+ RUN pip install --no-cache-dir -r requirements.txt
569
+
570
+ COPY . .
571
+ RUN useradd -m -u 1000 appuser && chown -R appuser:appuser /app
572
+ USER appuser
573
+
574
+ CMD ["bash", "start_hf.sh"]
575
+ ```
576
+
577
+ #### Key `requirements.txt` Additions
578
+
579
+ ```txt
580
+ huggingface_hub # HF Inference API client
581
+ groq>=0.9.0 # Groq Vision API client
582
+ google-genai>=1.0.0 # Optional: Google Gemini (requires billing for cloud IPs)
583
+ pytesseract>=0.3.10 # Local OCR fallback
584
+ pillow>=10.0.0
585
+ ```
586
+
587
+ #### Deployment Steps
588
+
589
+ 1. **Create a HuggingFace Space** at https://huggingface.co/spaces
590
+ - SDK: **Docker**
591
+ - Visibility: Public or Private
592
+
593
+ 2. **Push your repository** to the Space's git remote:
594
+ ```bash
595
+ git remote add space https://huggingface.co/spaces/<your-username>/<space-name>
596
+ git push space main
597
+ ```
598
+
599
+ 3. **Add secrets** in Space Settings (see table above). Do **not** hardcode secrets in the Dockerfile or any committed file.
600
+
601
+ 4. **Factory Reboot** the Space after adding secrets to trigger a clean rebuild with the new environment variables.
602
+
603
+ 5. **Monitor the build logs** — a successful startup shows:
604
+ ```
605
+ [GRANITE_VQA] Target Model: meta-llama/llama-4-scout-17b-16e-instruct (via Groq Vision)
606
+ [INFO] CLOUD MODE: Initializing Official HF InferenceClient (Qwen/Qwen2.5-Coder-7B-Instruct)
607
+ INFO: Uvicorn running on http://0.0.0.0:7860
608
+ ```
609
+
610
+ #### Important Notes on Line Endings
611
+
612
+ HuggingFace containers run Linux. If you develop on Windows, your shell scripts will have `\r\n` (CRLF) line endings, which cause `bad interpreter` errors on Linux. Add this to your `Dockerfile` to strip them automatically:
613
+
614
+ ```dockerfile
615
+ RUN sed -i 's/\r$//' start_hf.sh && chmod +x start_hf.sh
616
+ ```
617
+
618
+ Alternatively, configure Git to normalize line endings:
619
+ ```bash
620
+ git config core.autocrlf input
621
+ ```
622
+
623
+
624
+ ---
625
+
626
+ ## Project Summary
627
+
628
+ This project demonstrates that a self-correcting, multi-modal AI pipeline can be built and deployed entirely on consumer hardware through careful architectural decisions: progressive SQL generation with semantic validation, unified MCP-based tool access across data modalities, dynamic VRAM orchestration to prevent memory exhaustion, and a hybrid containerization strategy that preserves native GPU performance while maintaining deployment portability.
629
+
630
+ The system was developed iteratively, with each architectural decision — from model selection to validation logic to infrastructure design — informed by observed failure modes and measured outcomes rather than theoretical assumptions.
631
+
632
+ ---
633
+ *Built with ❤️ for advanced Agentic Data Engineering.*
app.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hugging Face Spaces entrypoint — Gradio SDK wrapper
3
+ ====================================================
4
+
5
+ HF Spaces moved the Docker SDK to a paid tier, so this Gradio-SDK Space
6
+ replicates the exact same three-service architecture the Docker image used:
7
+
8
+ this process (port 7860, public)
9
+ ├── Agent.worker → spawned uvicorn :8700 (Text2SQL / DocVQA backend)
10
+ ├── Agent.mcp_server → spawned uvicorn :8701 (MCP tool server)
11
+ └── web.app FastAPI → serves the sepia UI + /api proxies on :7860
12
+
13
+ A minimal Gradio Blocks page is mounted at ``/gradio-lp`` purely so the
14
+ Gradio-SDK runtime sees a registered Blocks application — the real UI is
15
+ the sepia web app at ``/``.
16
+
17
+ Secrets (Space settings → Variables and Secrets, never baked into the code):
18
+ HF_API_TOKEN — HF Inference API, Text-to-SQL on
19
+ Qwen/Qwen2.5-Coder-7B-Instruct
20
+ GROQ_API_KEY — Groq vision VQA (free tier)
21
+
22
+ No DB_CONNECTION_URL is required — the bundled authentic demo employee
23
+ SQLite database (employee-sample-database/sqlite/dataset_small/employee.db)
24
+ auto-activates as the demo_employee profile.
25
+ """
26
+ import os
27
+ import sys
28
+ import subprocess
29
+ from pathlib import Path
30
+
31
+ ROOT = Path(__file__).resolve().parent
32
+
33
+
34
+ # -----------------------------------------------------------------------------
35
+ # Background services (same as start_hf.sh in the Docker image)
36
+ # -----------------------------------------------------------------------------
37
+ def _spawn(module: str, port: int, name: str) -> subprocess.Popen:
38
+ """Start a uvicorn service; output streams into the Space log viewer."""
39
+ print(f"[LAUNCHER] starting {name} on :{port} ...", flush=True)
40
+ return subprocess.Popen(
41
+ [sys.executable, "-u", "-m", "uvicorn", module,
42
+ "--host", "0.0.0.0", "--port", str(port)],
43
+ cwd=str(ROOT),
44
+ )
45
+
46
+
47
+ _worker = _spawn("Agent.worker:app", 8700, "backend worker")
48
+ _mcp = _spawn("Agent.mcp_server:app", 8701, "MCP tool server")
49
+
50
+ # -----------------------------------------------------------------------------
51
+ # Web UI: our existing FastAPI app, with a tiny Gradio shell mounted beside it
52
+ # so the Gradio-SDK runtime is satisfied.
53
+ # -----------------------------------------------------------------------------
54
+ import gradio as gr # noqa: E402 (preinstalled in the Gradio-SDK runtime)
55
+ from web.app import app as fastapi_app # noqa: E402
56
+
57
+ with gr.Blocks() as _lp:
58
+ gr.Markdown(
59
+ "**QueryLens** — the full sepia UI is served at this Space's root `/`.\n\n"
60
+ "This page is only an anchor for the Gradio runtime."
61
+ )
62
+ gr.HTML('<a href="/" style="text-decoration:none;font-weight:600;">← Open the QueryLens UI</a>')
63
+
64
+ app = gr.mount_gradio_app(fastapi_app, _lp, path="/gradio-lp")
65
+
66
+
67
+ if __name__ == "__main__":
68
+ import uvicorn
69
+
70
+ port = int(os.environ.get("PORT", "7860"))
71
+ print(f"[LAUNCHER] QueryLens web UI live on http://0.0.0.0:{port}", flush=True)
72
+ uvicorn.run(app, host="0.0.0.0", port=port)
docker-compose.yml ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ # Main Agentic Application (worker :8700, MCP tool server :8701, web UI :7860)
5
+ demo-agent-app:
6
+ build: .
7
+ container_name: demo-agent-app
8
+ restart: unless-stopped
9
+ env_file: Agent/.env
10
+ environment:
11
+ - OLLAMA_BASE_URL=http://172.27.224.1:11434
12
+ - LLM_CTX=4096
13
+ deploy:
14
+ resources:
15
+ limits:
16
+ cpus: '2.0'
17
+ memory: 4G
18
+ ports:
19
+ - "7860:7860" # Web UI (QueryLens)
20
+ - "8700:8700" # Worker API
21
+ - "8701:8701" # MCP tool server
22
+ depends_on:
23
+ demo-postgres:
24
+ condition: service_healthy
25
+ demo-mysql:
26
+ condition: service_healthy
27
+ volumes:
28
+ - ./Agent:/app/Agent
29
+ - ./web:/app/web
30
+ # Dynamic database profiles: uploaded schema files + profile registry
31
+ - demo-schema-uploads:/app/uploads/schemas
32
+ - demo-chat-store:/app/chat_store
33
+ networks:
34
+ - demo-net
35
+
36
+ # MySQL Sample Database (built-in employee demo)
37
+ demo-mysql:
38
+ image: mysql:8.0
39
+ container_name: demo-mysql
40
+ restart: unless-stopped
41
+ env_file: Agent/.env
42
+ ports:
43
+ - "${MYSQL_PORT:-3306}:3306"
44
+ volumes:
45
+ - ./employee-sample-database/mysql/dataset_small:/docker-entrypoint-initdb.d
46
+ - demo-mysql-data:/var/lib/mysql
47
+ networks:
48
+ - demo-net
49
+ healthcheck:
50
+ test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "--silent"]
51
+ interval: 5s
52
+ timeout: 5s
53
+ retries: 12
54
+ start_period: 30s
55
+
56
+ # PostgreSQL Sample Database (built-in employee demo)
57
+ demo-postgres:
58
+ image: postgres:15
59
+ container_name: demo-postgres
60
+ restart: unless-stopped
61
+ env_file: Agent/.env
62
+ ports:
63
+ - "${POSTGRES_PORT:-5432}:5432"
64
+ volumes:
65
+ - ./employee-sample-database/postgres/dataset_small:/docker-entrypoint-initdb.d
66
+ - demo-postgres-data:/var/lib/postgresql/data
67
+ networks:
68
+ - demo-net
69
+ healthcheck:
70
+ test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-postgres}"]
71
+ interval: 5s
72
+ timeout: 5s
73
+ retries: 12
74
+ start_period: 30s
75
+
76
+ volumes:
77
+ demo-mysql-data:
78
+ demo-postgres-data:
79
+ demo-schema-uploads:
80
+ demo-chat-store:
81
+
82
+ networks:
83
+ demo-net:
84
+ driver: bridge
requirements.txt ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core Frameworks
2
+ fastapi>=0.100.0
3
+ uvicorn>=0.23.0
4
+ sqlalchemy>=2.0.0
5
+ pydantic>=2.0.0
6
+ python-multipart>=0.0.6
7
+ pandas>=2.0.0
8
+
9
+ # Multi-Agent Orchestration
10
+ llama-index>=0.10.0
11
+ llama-index-core>=0.10.0
12
+ llama-index-llms-ollama>=0.1.2
13
+ llama-index-llms-huggingface-api
14
+ huggingface_hub
15
+
16
+ # Model Context Protocol
17
+ mcp>=0.1.0
18
+ sqlparse>=0.4.4
19
+
20
+ # HTTP & Async
21
+ requests>=2.31.0
22
+ httpx>=0.26.0
23
+ aiohttp>=3.9.0
24
+ psutil>=5.9.0
25
+
26
+ # Database Drivers
27
+ pymysql>=1.1.0
28
+ asyncpg>=0.29.0
29
+ psycopg2-binary>=2.9.0
30
+ aiomysql>=0.2.0
31
+ aiosqlite>=0.19.0
32
+
33
+ # Document Vision processing
34
+ pillow>=10.0.0
35
+ pytesseract>=0.3.10
36
+ google-genai>=1.0.0
37
+ groq>=0.9.0
38
+
39
+ # Environment
40
+ python-dotenv>=1.0.0
start_hf.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # ☁️ Cloud-Only Startup Script for Hugging Face Spaces
4
+ # All LLM calls are routed to Groq and HF Inference APIs via USE_HF_CLOUD=1
5
+ # Ollama is NOT used — image is kept lightweight to prevent HF storage purges.
6
+
7
+ echo "[HF-INIT] ===== Application Startup at $(date -u '+%Y-%m-%d %H:%M:%S') ====="
8
+
9
+ # 1. Start Backend Worker
10
+ echo "[HF-INIT] Starting Backend Worker on port 8700..."
11
+ python -u -m uvicorn "Agent.worker:app" --host 0.0.0.0 --port 8700 &
12
+
13
+ # 2. Start MCP Tool Server
14
+ echo "[HF-INIT] Starting MCP Tool Server on port 8701..."
15
+ python -m uvicorn "Agent.mcp_server:app" --host 0.0.0.0 --port 8701 &
16
+
17
+ # 3. Start Web UI
18
+ echo "[HF-INIT] Starting Web UI on port 7860..."
19
+ python -m uvicorn "web.app:app" --host 0.0.0.0 --port 7860 &
20
+
21
+ echo "[HF-INIT] All services started. Container is live."
22
+
23
+ # Keep the container alive
24
+ wait
upload_binaries.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ upload_binaries.py -- push binary files to a HF Space via the Xet backend.
3
+
4
+ HF Spaces now reject binary files on plain `git push`; the supported path is
5
+ `huggingface_hub` (>= 0.32 with `hf_xet`), which uploads through Xet storage.
6
+
7
+ Usage:
8
+ python upload_binaries.py -r OWNER/REPO -p path/in/repo.db -f local/file.db
9
+
10
+ Auth: uses your cached HF token (created by `huggingface-cli login`).
11
+ Skips the upload if the remote file already has identical bytes.
12
+ """
13
+ import argparse
14
+ import hashlib
15
+ import sys
16
+
17
+ from huggingface_hub import HfApi, hf_hub_download, get_token
18
+
19
+
20
+ def sha256_of(path: str) -> str:
21
+ h = hashlib.sha256()
22
+ with open(path, "rb") as fh:
23
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
24
+ h.update(chunk)
25
+ return h.hexdigest()
26
+
27
+
28
+ def main() -> int:
29
+ ap = argparse.ArgumentParser()
30
+ ap.add_argument("-r", "--repo", required=True, help="repo id, e.g. OWNER/SPACE")
31
+ ap.add_argument("-p", "--path-in-repo", required=True)
32
+ ap.add_argument("-f", "--file", required=True, help="local file to upload")
33
+ args = ap.parse_args()
34
+
35
+ if not get_token():
36
+ print("ERROR: no HF token cached. Run 'huggingface-cli login' (token needs write access) and retry.")
37
+ return 2
38
+
39
+ api = HfApi()
40
+ repo_type = "space" # this script targets Spaces ("OWNER/SPACE" ids)
41
+
42
+ remote = None
43
+ try:
44
+ remote = hf_hub_download(
45
+ repo_id=args.repo, repo_type=repo_type, filename=args.path_in_repo
46
+ )
47
+ except Exception:
48
+ remote = None
49
+
50
+ local_hash = sha256_of(args.file)
51
+ if remote is not None:
52
+ try:
53
+ if sha256_of(remote) == local_hash:
54
+ print(f"[XET] {args.path_in_repo} already identical on {args.repo} - skipping upload")
55
+ return 0
56
+ print(f"[XET] {args.path_in_repo} differs on the remote {args.repo} - uploading new revision")
57
+ except OSError:
58
+ pass
59
+
60
+ print(f"[XET] uploading {args.path_in_repo} ({args.file}) to {args.repo} ...")
61
+ api.upload_file(
62
+ repo_id=args.repo,
63
+ repo_type=repo_type,
64
+ path_in_repo=args.path_in_repo,
65
+ path_or_fileobj=args.file,
66
+ commit_message=f"Add binary demo database via Xet: {args.path_in_repo}",
67
+ )
68
+ print(f"[XET] uploaded OK (sha256 {local_hash[:12]}...)")
69
+ return 0
70
+
71
+
72
+ if __name__ == "__main__":
73
+ sys.exit(main())
web/app.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import httpx
3
+ import logging
4
+ import traceback
5
+ from typing import Optional
6
+ from fastapi import FastAPI, HTTPException, Request
7
+ from pydantic import BaseModel
8
+ from fastapi.staticfiles import StaticFiles
9
+ from fastapi.responses import FileResponse, JSONResponse
10
+ from fastapi.middleware.cors import CORSMiddleware
11
+
12
+ WORKER_URL = os.environ.get("WORKER_URL", "http://localhost:8700")
13
+ # Timeout (seconds) when calling the worker; re-execute and heavy queries can take longer.
14
+ # Make configurable via environment variable WORKER_TIMEOUT (default 300s).
15
+ WORKER_TIMEOUT = float(os.environ.get("WORKER_TIMEOUT", "450")) # Increased to 450s to handle complex queries
16
+
17
+ # Reusable AsyncClient to avoid per-request connection setup overhead
18
+ client: httpx.AsyncClient | None = None
19
+
20
+ app = FastAPI(title="Text2SQL Web API")
21
+ app.add_middleware(
22
+ CORSMiddleware,
23
+ allow_origins=["*"], # adjust in production
24
+ allow_credentials=True,
25
+ allow_methods=["*"],
26
+ allow_headers=["*"],
27
+ )
28
+
29
+ # Serve static frontend under /static and provide a root route
30
+ static_dir = os.path.join(os.path.dirname(__file__), 'static')
31
+ if os.path.isdir(static_dir):
32
+ app.mount("/static", StaticFiles(directory=static_dir, html=True), name="static")
33
+
34
+
35
+ @app.get("/")
36
+ async def root_index():
37
+ index_path = os.path.join(static_dir, 'index.html')
38
+ return FileResponse(index_path)
39
+
40
+ class QueryReq(BaseModel):
41
+ question: str
42
+ # Optional doc_id produced by a prior /upload-image call
43
+ doc_id: Optional[str] = None
44
+ # Explicit mode hint from client: 'text2sql' or 'ocr_qa'. When omitted, worker may auto-detect.
45
+ mode: Optional[str] = None
46
+
47
+ class OcrQAReq(BaseModel):
48
+ question: str
49
+ doc_id: str
50
+
51
+ class OcrQAResp(BaseModel):
52
+ doc_id: str
53
+ answer: str
54
+ used_llm: bool
55
+
56
+ @app.get('/health')
57
+ async def health():
58
+ return {"status": "ok"}
59
+
60
+ @app.post('/api/query')
61
+ async def api_query(req: QueryReq):
62
+ # Use a shared AsyncClient created at startup to avoid TCP/TLS/HTTP handshakes per request.
63
+ global client
64
+ if client is None:
65
+ # fallback to create a temporary client (shouldn't happen if startup ran)
66
+ client = httpx.AsyncClient(timeout=WORKER_TIMEOUT)
67
+ try:
68
+ payload = {"question": req.question}
69
+ # Forward explicit mode if provided so the worker doesn't infer from lingering doc_id
70
+ if getattr(req, 'mode', None):
71
+ payload['mode'] = req.mode
72
+ if getattr(req, 'doc_id', None):
73
+ payload['doc_id'] = req.doc_id
74
+ r = await client.post(f"{WORKER_URL}/query", json=payload)
75
+ r.raise_for_status()
76
+ return r.json()
77
+ except httpx.HTTPStatusError as e:
78
+ # Log the full traceback and response body for debugging
79
+ logging.error("Worker returned non-2xx status: %s", e.response.status_code)
80
+ logging.error("Response text: %s", getattr(e.response, 'text', str(e)))
81
+ logging.error(traceback.format_exc())
82
+ raise HTTPException(status_code=e.response.status_code, detail=getattr(e.response, 'text', str(e)))
83
+ except httpx.ReadTimeout as e:
84
+ # Worker took too long. Return a 504 gateway timeout with a helpful message.
85
+ logging.error("Timeout contacting worker after %ss: %s", WORKER_TIMEOUT, str(e))
86
+ logging.error(traceback.format_exc())
87
+ return JSONResponse(status_code=504, content={
88
+ "error": "worker_timeout",
89
+ "message": f"Worker did not respond within {WORKER_TIMEOUT} seconds. The query may be long-running (re-execute) or the worker is busy. Try increasing WORKER_TIMEOUT or running the worker with more resources.",
90
+ })
91
+ except Exception as e:
92
+ logging.error("Error contacting worker: %s", str(e))
93
+ logging.error(traceback.format_exc())
94
+ # Return a JSON response containing the error detail to help debugging from the client
95
+ return JSONResponse(status_code=500, content={"error": str(e), "trace": traceback.format_exc()})
96
+
97
+
98
+ @app.post('/api/ocr-qa')
99
+ async def api_ocr_qa(req: OcrQAReq):
100
+ global client
101
+ if client is None:
102
+ client = httpx.AsyncClient(timeout=WORKER_TIMEOUT)
103
+ try:
104
+ payload = {"question": req.question, "doc_id": req.doc_id}
105
+ r = await client.post(f"{WORKER_URL}/ocr-qa", json=payload)
106
+ r.raise_for_status()
107
+ return r.json()
108
+ except httpx.HTTPStatusError as e:
109
+ logging.error("Worker OCR QA non-2xx: %s", e.response.status_code)
110
+ logging.error("Response text: %s", getattr(e.response, 'text', str(e)))
111
+ return JSONResponse(status_code=e.response.status_code, content={"error": getattr(e.response, 'text', str(e))})
112
+ except Exception as e:
113
+ logging.error("Error contacting worker OCR QA: %s", str(e))
114
+ return JSONResponse(status_code=500, content={"error": str(e), "trace": traceback.format_exc()})
115
+
116
+
117
+ @app.on_event('startup')
118
+ async def startup_event():
119
+ global client
120
+ if client is None:
121
+ client = httpx.AsyncClient(timeout=WORKER_TIMEOUT)
122
+
123
+
124
+ @app.on_event('shutdown')
125
+ async def shutdown_event():
126
+ global client
127
+ if client is not None:
128
+ await client.aclose()
129
+
130
+
131
+ @app.post('/api/test')
132
+ async def api_test(req: QueryReq):
133
+ # Simple echo endpoint to verify POST handling without contacting the worker
134
+ return {"ok": True, "echo": req.question}
135
+
136
+
137
+ @app.post('/upload-image')
138
+ async def upload_image(file: bytes = None, request: Request = None):
139
+ """Proxy an image upload to the worker's /upload-image endpoint.
140
+
141
+ Accepts multipart/form-data file field 'file' from the browser.
142
+ Returns the worker JSON (doc_id, text_preview, image_url) on success.
143
+ """
144
+ # Use the request.form() to access the uploaded file
145
+ try:
146
+ form = await request.form()
147
+ f = form.get('file')
148
+ if f is None:
149
+ raise HTTPException(status_code=400, detail='file field is required')
150
+ # forward the file to the worker
151
+ files = {'file': (f.filename, await f.read(), f.content_type)}
152
+ async with httpx.AsyncClient(timeout=120) as c:
153
+ r = await c.post(f"{WORKER_URL}/upload-image", files=files)
154
+ r.raise_for_status()
155
+ return JSONResponse(status_code=200, content=r.json())
156
+ except HTTPException:
157
+ raise
158
+ except Exception as e:
159
+ logging.error('upload-image proxy failed: %s', str(e))
160
+ raise HTTPException(status_code=500, detail=str(e))
161
+
162
+
163
+ # ---------------------------------------------------------------------------
164
+ # Schema profile proxy endpoints — dynamic multi-database support
165
+ # ---------------------------------------------------------------------------
166
+
167
+ @app.get('/api/schemas')
168
+ async def api_schemas():
169
+ global client
170
+ try:
171
+ r = await client.get(f"{WORKER_URL}/schemas")
172
+ r.raise_for_status()
173
+ return r.json()
174
+ except httpx.HTTPStatusError as e:
175
+ return JSONResponse(status_code=e.response.status_code,
176
+ content={"error": getattr(e.response, 'text', str(e))})
177
+ except Exception as e:
178
+ logging.error('schemas list proxy failed: %s', str(e))
179
+ return JSONResponse(status_code=500, content={"error": str(e)})
180
+
181
+
182
+ class AddSchemaReq(BaseModel):
183
+ name: str
184
+ connection_url: str
185
+ activate: Optional[bool] = True
186
+
187
+
188
+ @app.post('/api/schemas/add')
189
+ async def api_schemas_add(req: AddSchemaReq):
190
+ global client
191
+ try:
192
+ r = await client.post(f"{WORKER_URL}/schemas/add", json=req.model_dump(),
193
+ timeout=WORKER_TIMEOUT)
194
+ r.raise_for_status()
195
+ return r.json()
196
+ except httpx.HTTPStatusError as e:
197
+ return JSONResponse(status_code=e.response.status_code,
198
+ content={"error": getattr(e.response, 'text', str(e))})
199
+ except Exception as e:
200
+ logging.error('schemas add proxy failed: %s', str(e))
201
+ return JSONResponse(status_code=500, content={"error": str(e)})
202
+
203
+
204
+ @app.post('/api/schemas/add-file')
205
+ async def api_schemas_add_file(request: Request):
206
+ """Proxy a schema file upload (.sqlite/.db/.csv) to the worker."""
207
+ global client
208
+ try:
209
+ form = await request.form()
210
+ f = form.get('file')
211
+ if f is None:
212
+ raise HTTPException(status_code=400, detail='file field is required')
213
+ data = {'name': form.get('name') or '', 'activate': form.get('activate', 'true')}
214
+ files = {'file': (f.filename, await f.read(), f.content_type)}
215
+ # DB init can be slow on first connect; generous timeout
216
+ async with httpx.AsyncClient(timeout=300) as c:
217
+ r = await c.post(f"{WORKER_URL}/schemas/add-file", files=files, data=data)
218
+ r.raise_for_status()
219
+ return r.json()
220
+ except HTTPException:
221
+ raise
222
+ except httpx.HTTPStatusError as e:
223
+ return JSONResponse(status_code=e.response.status_code,
224
+ content={"error": getattr(e.response, 'text', str(e))})
225
+ except Exception as e:
226
+ logging.error('schemas add-file proxy failed: %s', str(e))
227
+ return JSONResponse(status_code=500, content={"error": str(e)})
228
+
229
+
230
+ @app.post('/api/schemas/switch/{profile_id}')
231
+ async def api_schemas_switch(profile_id: str):
232
+ global client
233
+ try:
234
+ r = await client.post(f"{WORKER_URL}/schemas/switch/{profile_id}",
235
+ timeout=WORKER_TIMEOUT)
236
+ r.raise_for_status()
237
+ return r.json()
238
+ except httpx.HTTPStatusError as e:
239
+ return JSONResponse(status_code=e.response.status_code,
240
+ content={"error": getattr(e.response, 'text', str(e))})
241
+ except Exception as e:
242
+ logging.error('schemas switch proxy failed: %s', str(e))
243
+ return JSONResponse(status_code=500, content={"error": str(e)})
244
+
245
+
246
+ @app.delete('/api/schemas/{profile_id}')
247
+ async def api_schemas_delete(profile_id: str):
248
+ global client
249
+ try:
250
+ r = await client.delete(f"{WORKER_URL}/schemas/{profile_id}")
251
+ r.raise_for_status()
252
+ return r.json()
253
+ except httpx.HTTPStatusError as e:
254
+ return JSONResponse(status_code=e.response.status_code,
255
+ content={"error": getattr(e.response, 'text', str(e))})
256
+ except Exception as e:
257
+ logging.error('schemas delete proxy failed: %s', str(e))
258
+ return JSONResponse(status_code=500, content={"error": str(e)})
259
+
260
+
261
+ @app.get('/api/schema/current')
262
+ async def api_schema_current():
263
+ global client
264
+ try:
265
+ r = await client.get(f"{WORKER_URL}/schema/current")
266
+ r.raise_for_status()
267
+ return r.json()
268
+ except httpx.HTTPStatusError as e:
269
+ return JSONResponse(status_code=e.response.status_code,
270
+ content={"error": getattr(e.response, 'text', str(e))})
271
+ except Exception as e:
272
+ logging.error('schema current proxy failed: %s', str(e))
273
+ return JSONResponse(status_code=500, content={"error": str(e)})
274
+
275
+
276
+ @app.get('/api/test')
277
+ async def api_test_get():
278
+ return {"ok": True, "msg": "POST to /api/test with JSON {question: ...} to echo"}
279
+
280
+ if __name__ == '__main__':
281
+ import uvicorn
282
+ port = int(os.environ.get('WEB_PORT', 8000))
283
+ uvicorn.run(app, host='0.0.0.0', port=port)
web/static/app.js ADDED
@@ -0,0 +1,836 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const askBtn = document.getElementById('ask');
2
+ const questionEl = document.getElementById('question');
3
+ const answerEl = document.getElementById('answer');
4
+ const sqlEl = document.getElementById('sql');
5
+ const memoryEl = document.getElementById('memory');
6
+ const querycraftEl = document.getElementById('querycraft');
7
+ const presenterEl = document.getElementById('presenter');
8
+ const uploadInput = document.getElementById('upload');
9
+ const uploadBtn = document.getElementById('uploadBtn');
10
+ const uploadStatus = document.getElementById('uploadStatus');
11
+ const uploadControls = document.getElementById('uploadControls');
12
+ const modeToggle = document.getElementById('modeToggle');
13
+ let currentDocId = null;
14
+ let currentMode = 'text2sql';
15
+ const statusEl = document.getElementById('status');
16
+ const timeEl = document.getElementById('time');
17
+ const recalcBtn = document.getElementById('recalc');
18
+ const spinner = document.getElementById('spinner');
19
+ const spinnerText = document.getElementById('spinnerText');
20
+ const askBtnEl = askBtn;
21
+
22
+ // Mode toggle logic
23
+ modeToggle.addEventListener('change', function() {
24
+ currentMode = modeToggle.value;
25
+ console.log('[DEBUG] Mode changed to:', currentMode); // Debug log
26
+ if(currentMode === 'ocr_qa') {
27
+ uploadControls.classList.remove('hidden');
28
+ console.log('[DEBUG] Upload controls shown'); // Debug log
29
+ } else {
30
+ uploadControls.classList.add('hidden');
31
+ currentDocId = null;
32
+ uploadStatus.textContent = 'No upload';
33
+ uploadStatus.className = 'status-text';
34
+ console.log('[DEBUG] Upload controls hidden'); // Debug log
35
+ }
36
+ });
37
+
38
+ // Initialize UI state
39
+ console.log('[DEBUG] Initial mode:', currentMode); // Debug log
40
+ if(currentMode === 'ocr_qa') {
41
+ uploadControls.classList.remove('hidden');
42
+ } else {
43
+ uploadControls.classList.add('hidden');
44
+ }
45
+
46
+ // Helper to programmatically switch to OCR Q&A mode
47
+ function switchToOcrQaMode() {
48
+ if (modeToggle.value !== 'ocr_qa') {
49
+ modeToggle.value = 'ocr_qa';
50
+ currentMode = 'ocr_qa';
51
+ uploadControls.classList.remove('hidden');
52
+ // Fire a change event so any listeners update state consistently
53
+ const ev = new Event('change', { bubbles: true });
54
+ modeToggle.dispatchEvent(ev);
55
+ console.log('[DEBUG] Switched to OCR Q&A mode');
56
+ }
57
+ }
58
+
59
+ // Extract mode change logic into a function so it can be called directly
60
+ function onModeChange() {
61
+ currentMode = modeToggle.value;
62
+ console.log('[DEBUG] onModeChange called, mode:', currentMode); // Debug log
63
+ if(currentMode === 'ocr_qa') {
64
+ uploadControls.classList.remove('hidden');
65
+ console.log('[DEBUG] Upload controls shown via onModeChange'); // Debug log
66
+ } else {
67
+ uploadControls.classList.add('hidden');
68
+ currentDocId = null;
69
+ uploadStatus.textContent = 'No upload';
70
+ uploadStatus.className = 'status-text';
71
+ console.log('[DEBUG] Upload controls hidden via onModeChange'); // Debug log
72
+ }
73
+ }
74
+
75
+ // Mode toggle logic
76
+ modeToggle.addEventListener('change', onModeChange);
77
+
78
+ // Upload handler: create a temporary file input on demand to avoid issues with a permanently hidden input.
79
+ if (uploadBtn) {
80
+ uploadBtn.addEventListener('click', () => {
81
+ // If not in OCR Q&A mode, switch and highlight, then open file picker after a delay
82
+ if (modeToggle.value !== 'ocr_qa') {
83
+ switchToOcrQaMode();
84
+ // Visually highlight the dropdown to show the switch
85
+ modeToggle.style.boxShadow = '0 0 0 3px rgba(15, 98, 254, 0.2)';
86
+ modeToggle.style.transition = 'box-shadow 0.2s';
87
+ setTimeout(() => {
88
+ modeToggle.style.boxShadow = '';
89
+ // Now open the file picker
90
+ const tmp = document.createElement('input');
91
+ tmp.type = 'file';
92
+ tmp.accept = 'image/*';
93
+ tmp.style.position = 'absolute';
94
+ tmp.style.left = '-9999px';
95
+ document.body.appendChild(tmp);
96
+
97
+ tmp.addEventListener('change', async () => {
98
+ const files = tmp.files;
99
+ if (!files || files.length === 0) {
100
+ uploadStatus.textContent = 'No file selected';
101
+ document.body.removeChild(tmp);
102
+ return;
103
+ }
104
+ switchToOcrQaMode();
105
+ uploadStatus.textContent = 'Uploading...';
106
+ uploadStatus.className = 'status-text text-warning';
107
+ const fd = new FormData();
108
+ fd.append('file', files[0]);
109
+ try {
110
+ const r = await fetch('/upload-image', { method: 'POST', body: fd });
111
+ if (!r.ok) {
112
+ const j = await r.json().catch(()=>({}));
113
+ uploadStatus.textContent = 'Upload failed: ' + (j.detail || r.statusText);
114
+ uploadStatus.className = 'status-text text-error';
115
+ document.body.removeChild(tmp);
116
+ return;
117
+ }
118
+ const j = await r.json();
119
+ currentDocId = j.doc_id;
120
+ uploadStatus.textContent = `Uploaded (doc_id=${currentDocId})`;
121
+ uploadStatus.className = 'status-text text-success';
122
+ } catch (e) {
123
+ uploadStatus.textContent = 'Upload error: ' + String(e);
124
+ uploadStatus.className = 'status-text text-error';
125
+ }
126
+ document.body.removeChild(tmp);
127
+ });
128
+ tmp.click();
129
+ }, 350); // 350ms to allow UI to update and user to see the switch
130
+ return;
131
+ }
132
+ // Already in OCR Q&A mode: open file picker immediately
133
+ const tmp = document.createElement('input');
134
+ tmp.type = 'file';
135
+ tmp.accept = 'image/*';
136
+ tmp.style.position = 'absolute';
137
+ tmp.style.left = '-9999px';
138
+ document.body.appendChild(tmp);
139
+
140
+ tmp.addEventListener('change', async () => {
141
+ const files = tmp.files;
142
+ if (!files || files.length === 0) {
143
+ uploadStatus.textContent = 'No file selected';
144
+ uploadStatus.className = 'status-text';
145
+ document.body.removeChild(tmp);
146
+ return;
147
+ }
148
+ switchToOcrQaMode();
149
+ uploadStatus.textContent = 'Uploading...';
150
+ uploadStatus.className = 'status-text text-warning';
151
+ const fd = new FormData();
152
+ fd.append('file', files[0]);
153
+ try {
154
+ const r = await fetch('/upload-image', { method: 'POST', body: fd });
155
+ if (!r.ok) {
156
+ const j = await r.json().catch(()=>({}));
157
+ uploadStatus.textContent = 'Upload failed: ' + (j.detail || r.statusText);
158
+ uploadStatus.className = 'status-text text-error';
159
+ document.body.removeChild(tmp);
160
+ return;
161
+ }
162
+ const j = await r.json();
163
+ currentDocId = j.doc_id;
164
+ uploadStatus.textContent = `Uploaded (doc_id=${currentDocId})`;
165
+ uploadStatus.className = 'status-text text-success';
166
+ } catch (e) {
167
+ uploadStatus.textContent = 'Upload error: ' + String(e);
168
+ uploadStatus.className = 'status-text text-error';
169
+ }
170
+ document.body.removeChild(tmp);
171
+ });
172
+ tmp.click();
173
+ });
174
+ }
175
+
176
+ function setRunning(running){
177
+ if(running){
178
+ askBtnEl.disabled = true;
179
+ recalcBtn.disabled = true;
180
+ questionEl.disabled = true;
181
+ spinner.classList.remove('hidden');
182
+ spinnerText.classList.remove('hidden');
183
+ spinnerText.textContent = 'Processing...';
184
+ // hide the small status text while spinner is active
185
+ statusEl.textContent = '';
186
+ console.log('[DEBUG] Loading state: ON, spinner should be visible'); // Debug log
187
+ } else {
188
+ askBtnEl.disabled = false;
189
+ recalcBtn.disabled = false;
190
+ questionEl.disabled = false;
191
+ spinner.classList.add('hidden');
192
+ spinnerText.classList.add('hidden');
193
+ // restore default status
194
+ statusEl.textContent = 'Ready';
195
+ console.log('[DEBUG] Loading state: OFF, spinner should be hidden'); // Debug log
196
+ }
197
+ }
198
+
199
+ function renderPresenterTrace(text){
200
+ if(!text) return '—';
201
+ // Split traces into chunks separated by blank lines and render as collapsible
202
+ const parts = String(text).split(/\n\s*\n/).filter(Boolean);
203
+ const container = document.createElement('div');
204
+ parts.forEach((p, i) => {
205
+ const d = document.createElement('details');
206
+ const summary = document.createElement('summary');
207
+ summary.textContent = p.split('\n')[0].slice(0,80);
208
+ summary.style.cursor = 'pointer';
209
+ summary.style.padding = '0.5rem';
210
+ summary.style.borderRadius = '0.375rem';
211
+ summary.style.marginBottom = '0.5rem';
212
+ summary.style.backgroundColor = 'var(--bg-tertiary)';
213
+ const pre = document.createElement('pre');
214
+ pre.style.whiteSpace = 'pre-wrap';
215
+ pre.style.fontSize = '0.75rem';
216
+ pre.style.padding = '0.75rem';
217
+ pre.style.backgroundColor = 'var(--bg-secondary)';
218
+ pre.style.borderRadius = '0.375rem';
219
+ pre.style.margin = '0';
220
+ pre.textContent = p;
221
+ d.appendChild(summary);
222
+ d.appendChild(pre);
223
+ if(i===0) d.open = true;
224
+ container.appendChild(d);
225
+ });
226
+ return container;
227
+ }
228
+
229
+ // small helper to escape HTML
230
+ const esc = s => String(s || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
231
+
232
+ // Detect if text contains a pipe/markdown table and return true
233
+ function isMarkdownTable(text){
234
+ if(!text) return false;
235
+ const lines = String(text).split(/\r?\n/).map(l=>l.trim()).filter(Boolean);
236
+ if(lines.length < 2) return false;
237
+ // Count lines that contain pipe separators
238
+ const pipeLines = lines.filter(l => l.includes('|'));
239
+ if(pipeLines.length < 2) return false;
240
+ // If the second line is a markdown separator like | --- | --- | or ---|---
241
+ const second = lines[1];
242
+ if(/^\s*\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?\s*$/.test(second)) return true;
243
+ // Otherwise, if majority of non-empty lines contain pipes, treat as table
244
+ return (pipeLines.length / lines.length) >= 0.5;
245
+ }
246
+
247
+ // Parse a simple markdown/pipe table into a DOM <table>
248
+ function parseMarkdownTable(text){
249
+ const lines = String(text).split(/\r?\n/).map(l=>l.trim()).filter(Boolean);
250
+ // find the first contiguous block of pipe lines
251
+ let start = -1, end = -1;
252
+ for(let i=0;i<lines.length;i++){
253
+ if(lines[i].includes('|')){ start = i; break; }
254
+ }
255
+ if(start === -1) return null;
256
+ for(let i=start;i<lines.length;i++){
257
+ if(!lines[i].includes('|')){ end = i; break; }
258
+ }
259
+ if(end === -1) end = lines.length;
260
+ const block = lines.slice(start, end);
261
+ const rows = block.map(r => {
262
+ let s = r;
263
+ if(s.startsWith('|')) s = s.slice(1);
264
+ if(s.endsWith('|')) s = s.slice(0,-1);
265
+ return s.split('|').map(c => c.trim());
266
+ });
267
+
268
+ // If second row is separator, treat first row as header
269
+ let header = null;
270
+ if(rows.length >= 2 && rows[1].every(c => /^:?-{3,}:?$/.test(c))) {
271
+ header = rows[0];
272
+ rows.splice(0,2);
273
+ }
274
+
275
+ const table = document.createElement('table');
276
+ table.className = 'answer-table';
277
+ const thead = document.createElement('thead');
278
+ const tbody = document.createElement('tbody');
279
+
280
+ if(header){
281
+ const tr = document.createElement('tr');
282
+ header.forEach(h => { const th = document.createElement('th'); th.textContent = h || ''; tr.appendChild(th); });
283
+ thead.appendChild(tr);
284
+ } else if(rows.length>0){
285
+ // use first row as header if no separator present
286
+ const tr = document.createElement('tr');
287
+ rows[0].forEach((_,i) => { const th = document.createElement('th'); th.textContent = `col ${i+1}`; tr.appendChild(th); });
288
+ thead.appendChild(tr);
289
+ }
290
+
291
+ rows.forEach(r => {
292
+ const tr = document.createElement('tr');
293
+ r.forEach(c => { const td = document.createElement('td'); td.textContent = c; tr.appendChild(td); });
294
+ tbody.appendChild(tr);
295
+ });
296
+
297
+ if(thead.childElementCount) table.appendChild(thead);
298
+ table.appendChild(tbody);
299
+
300
+ // Create enhanced table wrapper with controls
301
+ const wrapper = document.createElement('div');
302
+ wrapper.className = 'table-wrapper';
303
+
304
+ // Create table controls
305
+ const controls = document.createElement('div');
306
+ controls.className = 'table-controls';
307
+
308
+ const controlsLeft = document.createElement('div');
309
+ controlsLeft.className = 'table-controls-left';
310
+
311
+ const tableInfo = document.createElement('div');
312
+ tableInfo.className = 'table-info';
313
+ const rowCount = tbody.children.length;
314
+ const colCount = header ? header.length : (rows.length > 0 ? rows[0].length : 0);
315
+ tableInfo.textContent = `${rowCount} rows × ${colCount} columns`;
316
+
317
+ controlsLeft.appendChild(tableInfo);
318
+
319
+ const controlsRight = document.createElement('div');
320
+ controlsRight.className = 'table-controls-right';
321
+
322
+ const resizeControls = document.createElement('div');
323
+ resizeControls.className = 'table-resize-controls';
324
+
325
+ // Size control buttons
326
+ const sizes = [
327
+ { name: 'Compact', class: 'compact' },
328
+ { name: 'Comfortable', class: 'comfortable' },
329
+ { name: 'Spacious', class: 'spacious' }
330
+ ];
331
+
332
+ sizes.forEach((size, index) => {
333
+ const btn = document.createElement('button');
334
+ btn.textContent = size.name;
335
+ btn.className = 'table-resize-btn';
336
+ if (index === 1) btn.classList.add('active'); // Default to comfortable
337
+
338
+ btn.addEventListener('click', () => {
339
+ // Remove all size classes
340
+ table.classList.remove('compact', 'comfortable', 'spacious');
341
+ // Add selected size class
342
+ table.classList.add(size.class);
343
+
344
+ // Update active button
345
+ resizeControls.querySelectorAll('.table-resize-btn').forEach(b => b.classList.remove('active'));
346
+ btn.classList.add('active');
347
+ });
348
+
349
+ resizeControls.appendChild(btn);
350
+ });
351
+
352
+ controlsRight.appendChild(resizeControls);
353
+
354
+ controls.appendChild(controlsLeft);
355
+ controls.appendChild(controlsRight);
356
+
357
+ // Create table container
358
+ const container = document.createElement('div');
359
+ container.className = 'table-container';
360
+ container.appendChild(table);
361
+
362
+ wrapper.appendChild(controls);
363
+ wrapper.appendChild(container);
364
+
365
+ // Set default size
366
+ table.classList.add('comfortable');
367
+
368
+ return wrapper;
369
+ }
370
+
371
+ // heuristics: split logs into agent sections
372
+ function splitLogs(logs) {
373
+ const sections = {memory: '', querycraft: '', presenter: ''};
374
+ if (!logs) {
375
+ console.log('[DEBUG] splitLogs: No logs provided');
376
+ return sections;
377
+ }
378
+
379
+ console.log('[DEBUG] splitLogs: Input logs length:', logs.length);
380
+ console.log('[DEBUG] splitLogs: First 500 chars:', logs.substring(0, 500));
381
+ console.log('[DEBUG] splitLogs: Last 500 chars:', logs.substring(Math.max(0, logs.length - 500)));
382
+
383
+ // Normalize line endings
384
+ const lines = logs.replace(/\r/g,'').split('\n');
385
+ console.log('[DEBUG] splitLogs: Total lines:', lines.length);
386
+
387
+ // Look for explicit markers first
388
+ let mode = null;
389
+ let memoryMarkerFound = false;
390
+ let querycraftMarkerFound = false;
391
+ let presenterMarkerFound = false;
392
+
393
+ for (let i = 0; i < lines.length; i++) {
394
+ const line = lines[i];
395
+ const l = line.trim();
396
+
397
+ // Match the exact agent section headers from agentic_workflow.py
398
+ if (/=== MEMORY AGENT ===/i.test(l) || /INITIAL MEMORY/i.test(l)) {
399
+ mode = 'memory';
400
+ memoryMarkerFound = true;
401
+ console.log(`[DEBUG] splitLogs: Found MEMORY marker at line ${i}: "${l}"`);
402
+ continue;
403
+ }
404
+ if (/=== QUERY CRAFT AGENT ===/i.test(l) || /QUERY_CRAFT/i.test(l) || /MICRO-HINT/i.test(l)) {
405
+ mode = 'querycraft';
406
+ querycraftMarkerFound = true;
407
+ console.log(`[DEBUG] splitLogs: Found QUERYCRAFT marker at line ${i}: "${l}"`);
408
+ continue;
409
+ }
410
+ if (/=== RESULT PRESENTER AGENT ===/i.test(l) || /PRESENTER/i.test(l)) {
411
+ mode = 'presenter';
412
+ presenterMarkerFound = true;
413
+ console.log(`[DEBUG] splitLogs: Found PRESENTER marker at line ${i}: "${l}"`);
414
+ continue;
415
+ }
416
+ // Additional patterns to catch query craft related logs
417
+ if (/\[FAST\]/i.test(l) || /\[GEN\]/i.test(l) || /\[MICRO-HINT\]/i.test(l)) {
418
+ mode = 'querycraft';
419
+ console.log(`[DEBUG] splitLogs: Found QUERYCRAFT pattern at line ${i}: "${l}"`);
420
+ }
421
+ // Heuristic: SQL lines go to querycraft
422
+ if (/^(SELECT|WITH|INSERT|UPDATE|DELETE)\b/i.test(l)) {
423
+ mode = 'querycraft';
424
+ sections.querycraft += l + '\n';
425
+ console.log(`[DEBUG] splitLogs: Found SQL pattern at line ${i}, mode set to querycraft`);
426
+ continue;
427
+ }
428
+ if (!mode) {
429
+ // Seed with memory until a clearer marker appears
430
+ sections.memory += line + '\n';
431
+ } else {
432
+ sections[mode] += line + '\n';
433
+ }
434
+ }
435
+
436
+ console.log('[DEBUG] splitLogs: Markers found - Memory:', memoryMarkerFound, 'QueryCraft:', querycraftMarkerFound, 'Presenter:', presenterMarkerFound);
437
+ console.log('[DEBUG] splitLogs: Section lengths - Memory:', sections.memory.length, 'QueryCraft:', sections.querycraft.length, 'Presenter:', sections.presenter.length);
438
+ console.log('[DEBUG] splitLogs: Memory section preview:', sections.memory.substring(0, 200));
439
+ console.log('[DEBUG] splitLogs: QueryCraft section preview:', sections.querycraft.substring(0, 200));
440
+ console.log('[DEBUG] splitLogs: Presenter section preview:', sections.presenter.substring(0, 200));
441
+
442
+ return sections;
443
+ }
444
+
445
+ function findSQL(logs) {
446
+ if (!logs) return '';
447
+ // Primary: explicit markers
448
+ const markerRe = /<<<SQL_REVISED_START>>>([\s\S]*?)<<<SQL_REVISED_END>>>/m;
449
+ let m = logs.match(markerRe);
450
+ if (m) return m[1].trim();
451
+ const markerRe2 = /<<<SQL_START>>>([\s\S]*?)<<<SQL_END>>>/m;
452
+ m = logs.match(markerRe2);
453
+ if (m) return m[1].trim();
454
+ // Fallback: first standalone SQL-ish block up to semicolon
455
+ const fallback = logs.match(/^(?:.*?)(SELECT|WITH)[^;]{0,4000};/im);
456
+ if (fallback) {
457
+ const startIdx = fallback.index;
458
+ if (startIdx != null) {
459
+ const slice = logs.slice(startIdx).match(/([\s\S]*?;)/);
460
+ if (slice) return slice[1].trim();
461
+ }
462
+ }
463
+ return '';
464
+ }
465
+
466
+ async function runQuery(q){
467
+ if (!q) return alert('Please enter a question');
468
+ answerEl.textContent = 'Thinking...';
469
+ setRunning(true);
470
+ timeEl.textContent = '';
471
+ sqlEl.textContent = '-- SQL will appear here --';
472
+ memoryEl.textContent = querycraftEl.textContent = presenterEl.textContent = '—';
473
+
474
+ const startTime = Date.now();
475
+
476
+ try {
477
+ const body = { question: q, mode: currentMode };
478
+ if (currentMode === 'ocr_qa' && currentDocId) body.doc_id = currentDocId;
479
+ const res = await fetch('/api/query', {
480
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
481
+ body: JSON.stringify(body)
482
+ });
483
+ let j = null;
484
+ if (!res.ok) {
485
+ // Read the body EXACTLY once, then parse — reading .json() then .text()
486
+ // on the same Response throws "body stream already read".
487
+ const raw = await res.text().catch(() => '');
488
+ try { j = raw ? JSON.parse(raw) : null; } catch (err) { j = null; }
489
+ if (!j) {
490
+ answerEl.textContent = 'Error ' + res.status + ': ' + (raw || res.statusText || 'request failed');
491
+ setRunning(false);
492
+ return;
493
+ }
494
+ if (j.error === 'worker_timeout') { answerEl.textContent = 'Worker timeout: ' + (j.message || 'The worker did not respond in time.'); setRunning(false); return; }
495
+ answerEl.textContent = j.error || j.message || JSON.stringify(j);
496
+ if (j.trace) presenterEl.textContent = j.trace;
497
+ setRunning(false);
498
+ return;
499
+ }
500
+ j = await res.json();
501
+
502
+ const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
503
+
504
+ if (j.answer) {
505
+ // Render markdown/pipe tables as HTML tables for readability
506
+ if(isMarkdownTable(j.answer)){
507
+ const node = parseMarkdownTable(j.answer);
508
+ answerEl.innerHTML = '';
509
+ if(node) answerEl.appendChild(node);
510
+ else answerEl.textContent = j.answer;
511
+ } else {
512
+ // Non-table answers: preserve plain text
513
+ answerEl.textContent = j.answer;
514
+ }
515
+ } else answerEl.textContent = JSON.stringify(j, null, 2);
516
+
517
+ // Chart contract: render ECharts visualization if the worker attached one
518
+ renderChart(j.chart);
519
+ // A query round-tripped: the empty-state hint is no longer needed
520
+ if (!j.chart) {
521
+ const pending = document.getElementById('chartPending');
522
+ if (pending) pending.classList.add('hidden');
523
+ }
524
+
525
+ // Prefer direct sql field from worker, else derive from logs
526
+ if (j.sql) {
527
+ const codeEl = document.getElementById('sql');
528
+ codeEl.textContent = j.sql;
529
+ if(window.Prism && Prism.highlightElement) Prism.highlightElement(codeEl);
530
+ }
531
+
532
+ if (j.logs) {
533
+ console.log('[DEBUG] runQuery: Processing logs of length:', j.logs.length);
534
+ const sections = splitLogs(j.logs);
535
+ console.log('[DEBUG] runQuery: Sections received:', {
536
+ memory: sections.memory.length,
537
+ querycraft: sections.querycraft.length,
538
+ presenter: sections.presenter.length
539
+ });
540
+
541
+ const memoryContent = sections.memory.trim() || '—';
542
+ const querycraftContent = sections.querycraft.trim() || '—';
543
+ const presenterContent = sections.presenter.trim() || '';
544
+
545
+ console.log('[DEBUG] runQuery: Setting memory content length:', memoryContent.length);
546
+ console.log('[DEBUG] runQuery: Setting querycraft content length:', querycraftContent.length);
547
+ console.log('[DEBUG] runQuery: Setting presenter content length:', presenterContent.length);
548
+
549
+ memoryEl.textContent = memoryContent;
550
+ querycraftEl.textContent = querycraftContent;
551
+
552
+ if(presenterContent){
553
+ console.log('[DEBUG] runQuery: Rendering presenter trace');
554
+ const node = renderPresenterTrace(presenterContent);
555
+ presenterEl.innerHTML = '';
556
+ presenterEl.appendChild(node);
557
+ } else {
558
+ console.log('[DEBUG] runQuery: No presenter content, setting dash');
559
+ presenterEl.textContent = '—';
560
+ }
561
+ if (!j.sql) {
562
+ const sql = findSQL(j.logs) || '';
563
+ if (sql) {
564
+ const codeEl = document.getElementById('sql');
565
+ codeEl.textContent = sql;
566
+ if(window.Prism && Prism.highlightElement) Prism.highlightElement(codeEl);
567
+ }
568
+ }
569
+ } else {
570
+ console.log('[DEBUG] runQuery: No logs in response');
571
+ }
572
+
573
+ statusEl.textContent = 'Done';
574
+ timeEl.textContent = `${elapsed}s`;
575
+ setRunning(false);
576
+ } catch (e) {
577
+ answerEl.textContent = 'Error: ' + String(e);
578
+ setRunning(false);
579
+ }
580
+ }
581
+
582
+ askBtn.onclick = () => runQuery(questionEl.value.trim());
583
+
584
+ recalcBtn.onclick = () => {
585
+ const q = questionEl.value.trim();
586
+ if (!q) return alert('Please enter a question');
587
+ const normalized = q.replace(/^(?:re-execute\s+)+/i, '');
588
+ const prefixed = 're-execute ' + normalized;
589
+ // do not modify the visible textarea; send the prefixed query directly
590
+ runQuery(prefixed);
591
+ };
592
+
593
+ // Enter key support
594
+ questionEl.addEventListener('keydown', (e) => {
595
+ if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
596
+ e.preventDefault();
597
+ runQuery(questionEl.value.trim());
598
+ }
599
+ });
600
+
601
+ /* ============================================================================
602
+ * Phase 3/4 — chart rendering (ECharts, sepia palette)
603
+ * ========================================================================== */
604
+ const SEPIA_PALETTE = [
605
+ '#C15F3C', '#A39B7C', '#8A6F4D', '#B98A63', '#7E8A5A',
606
+ '#C9A227', '#6E7B6F', '#A9603F', '#5E5A4E', '#D9B08C',
607
+ ];
608
+ let chartInstance = null;
609
+
610
+ function renderChart(spec) {
611
+ const box = document.getElementById('chartBox');
612
+ const canvas = document.getElementById('chartCanvas');
613
+ const caption = document.getElementById('chartCaption');
614
+ const pending = document.getElementById('chartPending');
615
+ if (!box || !canvas) return;
616
+ if (!spec || !spec.type) { box.classList.add('hidden'); if (chartInstance) { chartInstance.dispose(); chartInstance = null; } return; }
617
+ if (typeof echarts === 'undefined') { box.classList.add('hidden'); return; }
618
+ if (pending) pending.classList.add('hidden');
619
+
620
+ box.classList.remove('hidden');
621
+ if (chartInstance) chartInstance.dispose();
622
+ chartInstance = echarts.init(canvas);
623
+
624
+ const base = {
625
+ backgroundColor: 'transparent',
626
+ color: SEPIA_PALETTE,
627
+ tooltip: { trigger: spec.type === 'pie' ? 'item' : 'axis' },
628
+ grid: { left: 12, right: 18, top: 42, bottom: 12, containLabel: true },
629
+ textStyle: { color: '#5E5A4E', fontFamily: 'Inter, sans-serif' },
630
+ };
631
+
632
+ let option = base;
633
+ const xAxis = {
634
+ type: 'category',
635
+ data: spec.x || [],
636
+ axisLine: { lineStyle: { color: '#D6CFBF' } },
637
+ axisLabel: { color: '#5E5A4E', rotate: (spec.x || []).length > 8 ? 30 : 0, hideOverlap: true },
638
+ };
639
+ const yAxis = {
640
+ type: 'value',
641
+ splitLine: { lineStyle: { color: '#EDE9DF' } },
642
+ axisLabel: { color: '#8B8678' },
643
+ };
644
+ const seriesData = (spec.series || []).map(s => ({ name: s.name, values: s.values || [] }));
645
+
646
+ if (spec.type === 'pie') {
647
+ const data = (spec.x || []).map((lab, i) => ({
648
+ name: lab,
649
+ value: (seriesData[0] && seriesData[0].values[i]) || 0,
650
+ }));
651
+ option = {
652
+ ...base, tooltip: { trigger: 'item' },
653
+ legend: { bottom: 0, textStyle: { color: '#5E5A4E', fontSize: 11 }, type: 'scroll' },
654
+ series: [{
655
+ type: 'pie', radius: ['38%', '68%'], center: ['50%', '46%'],
656
+ data, itemStyle: { borderColor: '#FAF9F5', borderWidth: 2, borderRadius: 6 },
657
+ label: { color: '#5E5A4E', fontSize: 11 },
658
+ }],
659
+ };
660
+ } else {
661
+ const key = spec.type === 'line' ? 'line' : 'bar';
662
+ option = {
663
+ ...base, xAxis, yAxis,
664
+ legend: seriesData.length > 1 ? { top: 4, textStyle: { color: '#5E5A4E', fontSize: 11 } } : undefined,
665
+ series: seriesData.map(s => ({
666
+ type: key, name: s.name, data: s.values,
667
+ ...(key === 'line' ? { smooth: true, symbolSize: 5 } : { itemStyle: { borderRadius: [4, 4, 0, 0] } }),
668
+ })),
669
+ };
670
+ }
671
+
672
+ chartInstance.setOption(option);
673
+ if (caption) {
674
+ caption.textContent = (spec.title || '') + (spec.rows_in_result ? ` · ${spec.rows_in_result} data points` : '');
675
+ }
676
+ }
677
+
678
+ window.addEventListener('resize', () => { if (chartInstance) chartInstance.resize(); });
679
+
680
+ /* ============================================================================
681
+ * Dynamic database profile manager (Phase 1 API + Phase 4 UI)
682
+ * ========================================================================== */
683
+ const schemaProfilesEl = document.getElementById('schemaProfiles');
684
+ const schemaTablesEl = document.getElementById('schemaTables');
685
+ const schemaNameEl = document.getElementById('schemaName');
686
+ const schemaUrlEl = document.getElementById('schemaUrl');
687
+ const schemaAddBtn = document.getElementById('schemaAddBtn');
688
+ const schemaFileBtn = document.getElementById('schemaFileBtn');
689
+ const dbBadge = document.getElementById('dbBadge');
690
+ const dbTag = document.getElementById('dbTag');
691
+
692
+ async function apiSchemas(method, path, body, isForm) {
693
+ const opts = { method, headers: {} };
694
+ if (body !== undefined) {
695
+ if (isForm) { opts.body = body; }
696
+ else { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); }
697
+ }
698
+ const r = await fetch(path, opts);
699
+ let j = null;
700
+ try { j = await r.json(); } catch (e) { j = null; }
701
+ if (!r.ok) throw new Error((j && (j.error || j.detail)) || r.statusText);
702
+ return j;
703
+ }
704
+
705
+ function setActiveProfileName(name) {
706
+ if (dbBadge) dbBadge.textContent = name || '—';
707
+ if (dbTag) dbTag.textContent = name || 'demo_employee';
708
+ }
709
+
710
+ async function refreshSchemaPanel() {
711
+ let data;
712
+ try { data = await apiSchemas('GET', '/api/schemas'); }
713
+ catch (e) {
714
+ if (schemaProfilesEl) schemaProfilesEl.innerHTML = '<div class="profile-item"><span class="profile-name">(schema service offline)</span></div>';
715
+ return;
716
+ }
717
+ const profiles = (data.profiles || []);
718
+ setActiveProfileName((profiles.find(p => p.active) || {}).name || '—');
719
+
720
+ if (schemaProfilesEl) {
721
+ schemaProfilesEl.innerHTML = '';
722
+ if (!profiles.length) {
723
+ schemaProfilesEl.innerHTML = '<div class="profile-item"><span class="profile-name">No profiles yet — add one below</span></div>';
724
+ }
725
+ for (const p of profiles) {
726
+ const item = document.createElement('div');
727
+ item.className = 'profile-item' + (p.active ? ' active' : '');
728
+ const dot = document.createElement('span');
729
+ dot.className = 'profile-dot' + (p.active ? ' on' : '');
730
+ const nm = document.createElement('span');
731
+ nm.className = 'profile-name'; nm.textContent = p.name; nm.title = p.db_url || '';
732
+ const kind = document.createElement('span');
733
+ kind.className = 'profile-kind'; kind.textContent = p.kind || 'user';
734
+ const actions = document.createElement('span'); actions.className = 'profile-actions';
735
+ if (!p.active) {
736
+ const sw = document.createElement('button');
737
+ sw.className = 'profile-btn'; sw.textContent = 'Switch';
738
+ sw.onclick = async () => {
739
+ sw.disabled = true; sw.textContent = '…';
740
+ try { await apiSchemas('POST', '/api/schemas/switch/' + p.id); await refreshSchemaPanel(); }
741
+ catch (e) { alert('Switch failed: ' + e.message); sw.disabled = false; sw.textContent = 'Switch'; }
742
+ };
743
+ actions.appendChild(sw);
744
+ }
745
+ const del = document.createElement('button');
746
+ del.className = 'profile-btn danger'; del.textContent = '×';
747
+ del.title = 'Remove profile';
748
+ del.onclick = async () => {
749
+ if (!confirm(`Remove profile "${p.name}"?`)) return;
750
+ try { await apiSchemas('DELETE', '/api/schemas/' + p.id); await refreshSchemaPanel(); }
751
+ catch (e) { alert('Delete failed: ' + e.message); }
752
+ };
753
+ actions.appendChild(del);
754
+ item.append(dot, nm, kind, actions);
755
+ schemaProfilesEl.appendChild(item);
756
+ }
757
+ }
758
+
759
+ // Current schema tables (best-effort)
760
+ try {
761
+ const cur = await apiSchemas('GET', '/api/schema/current');
762
+ if (schemaTablesEl) {
763
+ schemaTablesEl.innerHTML = '';
764
+ const tables = cur.tables || [];
765
+ if (!tables.length) { schemaTablesEl.innerHTML = ''; return; }
766
+ for (const t of tables.slice(0, 10)) {
767
+ const d = document.createElement('div');
768
+ d.className = 'tbl';
769
+ d.innerHTML = `<b>${escapeHtml(t.name)}</b> <span class="rc">(${t.row_count ?? '?'} rows · ${t.columns.length} cols)</span>`;
770
+ d.title = t.columns.join(', ');
771
+ schemaTablesEl.appendChild(d);
772
+ }
773
+ }
774
+ } catch (e) { /* schema detail endpoint optional */ }
775
+ }
776
+
777
+ function escapeHtml(s) {
778
+ return String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
779
+ }
780
+
781
+ async function addSchemaFromUrl() {
782
+ const name = (schemaNameEl && schemaNameEl.value.trim()) || '';
783
+ const url = (schemaUrlEl && schemaUrlEl.value.trim()) || '';
784
+ if (!name || !url) { alert('Provide both a profile name and a connection URL (or use file upload).'); return; }
785
+ schemaAddBtn.disabled = true; schemaAddBtn.textContent = 'Connecting…';
786
+ try {
787
+ await apiSchemas('POST', '/api/schemas/add', { name, connection_url: url });
788
+ schemaNameEl.value = ''; schemaUrlEl.value = '';
789
+ await refreshSchemaPanel();
790
+ statusEl.textContent = `Connected to "${name}"`;
791
+ } catch (e) {
792
+ alert('Connect failed: ' + e.message);
793
+ } finally {
794
+ schemaAddBtn.disabled = false; schemaAddBtn.textContent = 'Connect';
795
+ }
796
+ }
797
+
798
+ function addSchemaFromFile() {
799
+ const tmp = document.createElement('input');
800
+ tmp.type = 'file';
801
+ tmp.accept = '.sqlite,.db,.sqlite3,.csv';
802
+ tmp.style.position = 'absolute'; tmp.style.left = '-9999px';
803
+ document.body.appendChild(tmp);
804
+ tmp.addEventListener('change', async () => {
805
+ const f = tmp.files && tmp.files[0];
806
+ document.body.removeChild(tmp);
807
+ if (!f) return;
808
+ if (!schemaNameEl.value.trim()) schemaNameEl.value = f.name.replace(/\.[^.]+$/, '');
809
+ const fd = new FormData();
810
+ fd.append('file', f);
811
+ fd.append('name', schemaNameEl.value.trim());
812
+ fd.append('activate', 'true');
813
+ schemaFileBtn.disabled = true; schemaFileBtn.textContent = 'Importing…';
814
+ try {
815
+ await fetch('/api/schemas/add-file', { method: 'POST', body: fd }).then(async r => {
816
+ if (!r.ok) { const j = await r.json().catch(() => ({})); throw new Error(j.detail || r.statusText); }
817
+ return r.json();
818
+ });
819
+ await refreshSchemaPanel();
820
+ statusEl.textContent = `Imported "${schemaNameEl.value.trim()}"`;
821
+ schemaNameEl.value = '';
822
+ } catch (e) {
823
+ alert('Import failed: ' + e.message);
824
+ } finally {
825
+ schemaFileBtn.disabled = false; schemaFileBtn.textContent = 'Upload .sqlite / .csv';
826
+ }
827
+ });
828
+ tmp.click();
829
+ }
830
+
831
+ if (schemaAddBtn) schemaAddBtn.onclick = addSchemaFromUrl;
832
+ if (schemaFileBtn) schemaFileBtn.onclick = addSchemaFromFile;
833
+
834
+ // Initial load
835
+ refreshSchemaPanel();
836
+
web/static/index.html ADDED
@@ -0,0 +1,690 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+
4
+ <head>
5
+ <meta charset="utf-8" />
6
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
7
+ <title>QueryLens — Ask your data anything</title>
8
+ <link rel="icon"
9
+ href="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPGNpcmNsZSBjeD0iMTIiIGN5PSIxMiIgcj0iMTAiIGZpbGw9IiNDMTVGM0MiLz4KPHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeD0iNCIgeT0iNCBjbGFzcz0icXVlcnktaWNvbiI+CjxwYXRoIGQ9Ik0xMiAyVjdNMTIgN0wxNSAzTTUgOS41SDkuNU05LjUgOS41TDYgNk0xOSAxNC41SDE0LjVNMTQuNSAxNC41TDE4IDE4TTEyIDE3VjIyTTEyIDIyTDkgMTkiIHN0cm9rZT0id2hpdGUiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIi8+Cjwvc3ZnPjwvc3ZnPg==">
10
+
11
+ <!-- Fonts -->
12
+ <link rel="preconnect" href="https://fonts.googleapis.com">
13
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
14
+ <link
15
+ href="https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400;0,500;0,600;1,400&family=Inter:wght@300;400;500;600;700&display=swap"
16
+ rel="stylesheet">
17
+
18
+ <style>
19
+ :root {
20
+ /* ── Sepia / coffee palette (Claude-style) ─────────────────── */
21
+ --clay: #C15F3C; /* terracotta primary */
22
+ --clay-dark: #A84F2F;
23
+ --clay-soft: #E9C7B8;
24
+ --ocean: #5E6FA3; /* muted blue for info */
25
+
26
+ --bg-primary: #FAF9F5; /* ivory */
27
+ --bg-secondary: #F5F1EA; /* warm sand */
28
+ --bg-tertiary: #EFEAE0;
29
+ --card-bg: #FFFFFF;
30
+ --code-bg: #F0EEE6;
31
+
32
+ --border: #E5DFD3;
33
+ --border-light: #EDE9DF;
34
+ --border-strong: #D6CFBF;
35
+
36
+ --text-primary: #29261B; /* dark olive-brown */
37
+ --text-secondary: #5E5A4E;
38
+ --text-tertiary: #8B8678;
39
+ --text-on-clay: #FDF9F4;
40
+
41
+ --success: #6E7B4F;
42
+ --warning: #B98A23;
43
+ --error: #B04A32;
44
+
45
+ /* Spacing */
46
+ --space-1: 0.25rem;
47
+ --space-2: 0.5rem;
48
+ --space-3: 0.75rem;
49
+ --space-4: 1rem;
50
+ --space-5: 1.25rem;
51
+ --space-6: 1.5rem;
52
+ --space-8: 2rem;
53
+ --space-10: 2.5rem;
54
+
55
+ /* Shadows — warm and soft */
56
+ --shadow-sm: 0 1px 2px 0 rgb(74 60 35 / 0.05);
57
+ --shadow-md: 0 2px 6px -1px rgb(74 60 35 / 0.08), 0 1px 3px -1px rgb(74 60 35 / 0.06);
58
+ --shadow-lg: 0 8px 20px -6px rgb(74 60 35 / 0.12), 0 3px 8px -4px rgb(74 60 35 / 0.08);
59
+
60
+ --radius-sm: 6px;
61
+ --radius-md: 10px;
62
+ --radius-lg: 14px;
63
+ --radius-xl: 18px;
64
+
65
+ --transition-fast: 140ms ease;
66
+ --transition-normal: 240ms ease;
67
+ }
68
+
69
+ * , *::before, *::after { box-sizing: border-box; }
70
+
71
+ html, body {
72
+ height: 100%;
73
+ margin: 0;
74
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
75
+ background: var(--bg-primary);
76
+ color: var(--text-primary);
77
+ -webkit-font-smoothing: antialiased;
78
+ -moz-osx-font-smoothing: grayscale;
79
+ font-size: 15.5px;
80
+ line-height: 1.6;
81
+ }
82
+
83
+ h1, h2, h3, h4 { font-family: 'Lora', Georgia, serif; font-weight: 600; letter-spacing: -0.01em; }
84
+
85
+ ::selection { background: var(--clay-soft); color: var(--text-primary); }
86
+
87
+ /* ── Layout ──────────────────────────────────────────────────── */
88
+ .app-container {
89
+ min-height: 100vh;
90
+ display: flex;
91
+ flex-direction: column;
92
+ }
93
+
94
+ .header {
95
+ background: var(--bg-primary);
96
+ border-bottom: 1px solid var(--border-light);
97
+ padding: var(--space-5) var(--space-8);
98
+ }
99
+
100
+ .header-content {
101
+ max-width: 1240px;
102
+ margin: 0 auto;
103
+ display: flex;
104
+ align-items: center;
105
+ justify-content: space-between;
106
+ gap: var(--space-4);
107
+ }
108
+
109
+ .brand { display: flex; align-items: center; gap: 0.8rem; }
110
+
111
+ .brand-icon {
112
+ width: 40px; height: 40px;
113
+ border-radius: var(--radius-md);
114
+ background: var(--clay);
115
+ color: var(--text-on-clay);
116
+ display: grid; place-items: center;
117
+ box-shadow: var(--shadow-sm);
118
+ }
119
+
120
+ .brand-text h1 {
121
+ margin: 0; font-size: 1.32rem; line-height: 1.2; color: var(--text-primary);
122
+ }
123
+ .brand-text p {
124
+ margin: 1px 0 0; font-size: 0.82rem; color: var(--text-tertiary);
125
+ }
126
+
127
+ .header-tag {
128
+ font-size: 0.78rem;
129
+ color: var(--text-tertiary);
130
+ border: 1px solid var(--border);
131
+ background: var(--bg-secondary);
132
+ border-radius: 999px;
133
+ padding: 0.3rem 0.8rem;
134
+ white-space: nowrap;
135
+ }
136
+
137
+ .main-content {
138
+ max-width: 1240px;
139
+ width: 100%;
140
+ margin: 0 auto;
141
+ padding: var(--space-8) var(--space-8) var(--space-10);
142
+ flex: 1;
143
+ }
144
+
145
+ /* ── Query composer ──────────────────────────────────────────── */
146
+ .query-section { margin-bottom: var(--space-8); }
147
+
148
+ .query-body {
149
+ background: var(--card-bg);
150
+ border: 1px solid var(--border);
151
+ border-radius: var(--radius-lg);
152
+ box-shadow: var(--shadow-md);
153
+ padding: var(--space-5);
154
+ transition: border-color var(--transition-fast), box-shadow var(--transition-fast);
155
+ }
156
+ .query-body:focus-within {
157
+ border-color: var(--clay);
158
+ box-shadow: 0 0 0 3px rgb(193 95 60 / 0.10), var(--shadow-md);
159
+ }
160
+
161
+ .query-textarea {
162
+ width: 100%;
163
+ min-height: 96px;
164
+ border: none;
165
+ outline: none;
166
+ resize: vertical;
167
+ font-family: inherit;
168
+ font-size: 1.02rem;
169
+ color: var(--text-primary);
170
+ background: transparent;
171
+ line-height: 1.55;
172
+ }
173
+ .query-textarea::placeholder { color: var(--text-tertiary); }
174
+
175
+ .query-controls {
176
+ display: flex; align-items: center; gap: var(--space-3);
177
+ margin-top: var(--space-3);
178
+ padding-top: var(--space-3);
179
+ border-top: 1px solid var(--border-light);
180
+ flex-wrap: wrap;
181
+ }
182
+
183
+ .mode-select {
184
+ font-family: inherit;
185
+ font-size: 0.86rem;
186
+ color: var(--text-secondary);
187
+ background: var(--bg-secondary);
188
+ border: 1px solid var(--border);
189
+ border-radius: var(--radius-sm);
190
+ padding: 0.42rem 0.6rem;
191
+ cursor: pointer;
192
+ }
193
+
194
+ .btn {
195
+ display: inline-flex; align-items: center; gap: 0.45rem;
196
+ font-family: inherit; font-size: 0.9rem; font-weight: 600;
197
+ border-radius: var(--radius-sm);
198
+ padding: 0.5rem 1.05rem;
199
+ cursor: pointer;
200
+ border: 1px solid transparent;
201
+ transition: background var(--transition-fast), border-color var(--transition-fast),
202
+ transform var(--transition-fast), opacity var(--transition-fast);
203
+ }
204
+ .btn:active { transform: translateY(1px); }
205
+ .btn:disabled { opacity: 0.55; cursor: not-allowed; }
206
+
207
+ .btn-primary {
208
+ background: var(--clay);
209
+ color: var(--text-on-clay);
210
+ border-color: var(--clay);
211
+ }
212
+ .btn-primary:hover:not(:disabled) { background: var(--clay-dark); border-color: var(--clay-dark); }
213
+
214
+ .btn-secondary {
215
+ background: var(--card-bg);
216
+ color: var(--text-secondary);
217
+ border-color: var(--border-strong);
218
+ }
219
+ .btn-secondary:hover:not(:disabled) {
220
+ background: var(--bg-secondary);
221
+ color: var(--text-primary);
222
+ }
223
+
224
+ .status-area {
225
+ margin-left: auto;
226
+ display: flex; align-items: center; gap: 0.8rem;
227
+ font-size: 0.84rem; color: var(--text-tertiary);
228
+ }
229
+
230
+ .spinner {
231
+ width: 16px; height: 16px;
232
+ border: 2px solid var(--clay-soft);
233
+ border-top-color: var(--clay);
234
+ border-radius: 50%;
235
+ animation: spin 0.8s linear infinite;
236
+ }
237
+ @keyframes spin { to { transform: rotate(360deg); } }
238
+
239
+ .hidden { display: none !important; }
240
+
241
+ /* ── Results grid ────────────────────────────────────────────── */
242
+ .results-grid {
243
+ display: grid;
244
+ grid-template-columns: minmax(0, 1fr) 340px;
245
+ gap: var(--space-6);
246
+ align-items: start;
247
+ }
248
+ @media (max-width: 1020px) {
249
+ .results-grid { grid-template-columns: 1fr; }
250
+ }
251
+
252
+ .card {
253
+ background: var(--card-bg);
254
+ border: 1px solid var(--border);
255
+ border-radius: var(--radius-lg);
256
+ box-shadow: var(--shadow-sm);
257
+ overflow: hidden;
258
+ }
259
+ .card + .card { margin-top: var(--space-6); }
260
+
261
+ .card-header {
262
+ display: flex; align-items: center; gap: 0.5rem;
263
+ padding: 0.95rem var(--space-5);
264
+ border-bottom: 1px solid var(--border-light);
265
+ background: transparent;
266
+ }
267
+ .card-title {
268
+ margin: 0; font-size: 0.98rem; color: var(--text-primary);
269
+ display: flex; align-items: center; gap: 0.5rem;
270
+ font-family: 'Lora', Georgia, serif;
271
+ }
272
+ .card-title svg { color: var(--clay); }
273
+ .card-content { padding: var(--space-5); }
274
+
275
+ .answer-content { white-space: normal; color: var(--text-primary); }
276
+
277
+ /* ── Chart box (Phase 3 contract) ───────────────────────────── */
278
+ .chart-box {
279
+ margin-top: var(--space-4);
280
+ border: 1px solid var(--border-light);
281
+ background: var(--bg-secondary);
282
+ border-radius: var(--radius-md);
283
+ padding: var(--space-3);
284
+ }
285
+ .chart-pending {
286
+ margin-top: var(--space-4);
287
+ border: 1px dashed var(--border-light);
288
+ background: var(--bg-secondary);
289
+ border-radius: var(--radius-md);
290
+ padding: var(--space-4) var(--space-3);
291
+ font-size: 0.82rem;
292
+ color: var(--text-tertiary);
293
+ line-height: 1.6;
294
+ }
295
+ .chart-pending.hidden { display: none; }
296
+ #chartCanvas { width: 100%; height: 340px; }
297
+ .chart-caption {
298
+ margin: 0.4rem 0.2rem 0;
299
+ font-size: 0.78rem; color: var(--text-tertiary);
300
+ text-align: right;
301
+ }
302
+
303
+ /* ── SQL block ──────────────────────────────────────────────── */
304
+ details summary { outline: none; }
305
+ .sql-content {
306
+ margin: 0;
307
+ background: var(--code-bg);
308
+ border: 1px solid var(--border-light);
309
+ border-radius: var(--radius-md);
310
+ padding: var(--space-4);
311
+ overflow-x: auto;
312
+ font-size: 0.86rem;
313
+ line-height: 1.55;
314
+ }
315
+ code.language-sql, pre.sql-content code {
316
+ font-family: 'Cascadia Code', 'Fira Code', Consolas, monospace;
317
+ color: #4A4234;
318
+ }
319
+
320
+ /* ── Agent panels sidebar ───────────────────────────────────── */
321
+ .agent-panels { display: flex; flex-direction: column; gap: var(--space-4); }
322
+
323
+ .panel {
324
+ background: var(--card-bg);
325
+ border: 1px solid var(--border);
326
+ border-radius: var(--radius-lg);
327
+ box-shadow: var(--shadow-sm);
328
+ overflow: hidden;
329
+ }
330
+ .panel summary { list-style: none; }
331
+ .panel summary::-webkit-details-marker { display: none; }
332
+
333
+ .panel-header {
334
+ display: flex; align-items: center; justify-content: space-between;
335
+ padding: 0.8rem var(--space-4);
336
+ cursor: pointer;
337
+ user-select: none;
338
+ }
339
+ .panel-header:hover { background: var(--bg-secondary); }
340
+ .panel-title {
341
+ display: flex; align-items: center; gap: 0.5rem;
342
+ font-size: 0.84rem; font-weight: 600; color: var(--text-primary);
343
+ font-family: 'Lora', Georgia, serif;
344
+ }
345
+ .panel-title svg { color: var(--clay); }
346
+
347
+ .panel-content {
348
+ padding: 0 var(--space-4) var(--space-4);
349
+ font-size: 0.78rem;
350
+ color: var(--text-secondary);
351
+ max-height: 260px;
352
+ overflow-y: auto;
353
+ white-space: pre-wrap;
354
+ word-break: break-word;
355
+ font-family: Consolas, monospace;
356
+ }
357
+
358
+ /* ── Database panel ─────────────────────────────────────────── */
359
+ .db-badge {
360
+ margin-left: auto;
361
+ font-size: 0.7rem; font-weight: 600;
362
+ color: var(--clay);
363
+ background: rgb(193 95 60 / 0.10);
364
+ border: 1px solid rgb(193 95 60 / 0.25);
365
+ border-radius: 999px;
366
+ padding: 0.12rem 0.55rem;
367
+ }
368
+
369
+ .profile-list { display: flex; flex-direction: column; gap: 6px; padding: 0 var(--space-4) var(--space-3); }
370
+ .profile-item {
371
+ display: flex; align-items: center; gap: 0.5rem;
372
+ border: 1px solid var(--border);
373
+ background: var(--bg-secondary);
374
+ border-radius: var(--radius-sm);
375
+ padding: 0.5rem 0.65rem;
376
+ font-size: 0.8rem;
377
+ }
378
+ .profile-item.active { border-color: var(--clay); background: rgb(193 95 60 / 0.06); }
379
+ .profile-name { font-weight: 600; color: var(--text-primary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
380
+ .profile-kind { font-size: 0.68rem; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.04em; }
381
+ .profile-actions { margin-left: auto; display: flex; gap: 4px; }
382
+ .profile-btn {
383
+ border: 1px solid var(--border-strong);
384
+ background: var(--card-bg);
385
+ color: var(--text-secondary);
386
+ font-size: 0.7rem; font-weight: 600;
387
+ border-radius: 4px; padding: 2px 8px; cursor: pointer;
388
+ font-family: inherit;
389
+ }
390
+ .profile-btn:hover { border-color: var(--clay); color: var(--clay); }
391
+ .profile-btn.danger:hover { border-color: var(--error); color: var(--error); }
392
+ .profile-dot {
393
+ width: 7px; height: 7px; border-radius: 50%;
394
+ background: var(--border-strong); flex-shrink: 0;
395
+ }
396
+ .profile-dot.on { background: var(--success); }
397
+
398
+ .schema-add { padding: 0 var(--space-4) var(--space-4); border-top: 1px dashed var(--border); padding-top: var(--space-3); }
399
+ .schema-add label {
400
+ display: block; font-size: 0.72rem; font-weight: 600;
401
+ color: var(--text-tertiary); margin: 0.5rem 0 3px;
402
+ text-transform: uppercase; letter-spacing: 0.05em;
403
+ }
404
+ .schema-add input[type="text"] {
405
+ width: 100%; font-family: inherit; font-size: 0.8rem;
406
+ border: 1px solid var(--border); border-radius: var(--radius-sm);
407
+ padding: 0.4rem 0.55rem; color: var(--text-primary);
408
+ background: var(--card-bg);
409
+ }
410
+ .schema-add input[type="text"]:focus { outline: none; border-color: var(--clay); }
411
+ .schema-add .row2 { display: flex; gap: 6px; margin-top: 0.55rem; }
412
+ .schema-add .row2 .btn { flex: 1; justify-content: center; padding: 0.42rem 0.5rem; font-size: 0.78rem; }
413
+
414
+ .schema-tables { padding: 0 var(--space-4) var(--space-4); }
415
+ .schema-tables .tbl {
416
+ font-size: 0.75rem; color: var(--text-secondary);
417
+ border-bottom: 1px dotted var(--border);
418
+ padding: 3px 0;
419
+ }
420
+ .schema-tables .tbl b { color: var(--text-primary); font-weight: 600; }
421
+ .schema-tables .tbl .rc { color: var(--text-tertiary); font-size: 0.68rem; }
422
+
423
+ /* ── Footer ─────────────────────────────────────────────────── */
424
+ .footer {
425
+ text-align: center;
426
+ padding: var(--space-6);
427
+ color: var(--text-tertiary);
428
+ font-size: 0.8rem;
429
+ border-top: 1px solid var(--border-light);
430
+ }
431
+ .footer p { margin: 0; }
432
+
433
+ /* Markdown tables inside answer */
434
+ .answer-content table {
435
+ border-collapse: collapse;
436
+ width: 100%;
437
+ margin: 0.6rem 0;
438
+ font-size: 0.86rem;
439
+ }
440
+ .answer-content th, .answer-content td {
441
+ border: 1px solid var(--border);
442
+ padding: 0.4rem 0.7rem;
443
+ text-align: left;
444
+ }
445
+ .answer-content th { background: var(--bg-secondary); font-weight: 600; }
446
+ .answer-content tr:nth-child(even) td { background: var(--bg-secondary); }
447
+ </style>
448
+ </head>
449
+
450
+ <body>
451
+ <div class="app-container">
452
+ <!-- Header -->
453
+ <header class="header">
454
+ <div class="header-content">
455
+ <div class="brand">
456
+ <div class="brand-icon">
457
+ <svg width="22" height="22" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
458
+ <path d="M12 2V7M12 7L15 3M5 9.5H9.5M9.5 9.5L6 6M19 14.5H14.5M14.5 14.5L18 18M12 17V22M12 22L9 19"
459
+ stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
460
+ </svg>
461
+ </div>
462
+ <div class="brand-text">
463
+ <h1>QueryLens</h1>
464
+ <p>Ask your data anything.</p>
465
+ </div>
466
+ </div>
467
+ <span class="header-tag" id="dbTag">demo_employee</span>
468
+ </div>
469
+ </header>
470
+
471
+ <!-- Main Content -->
472
+ <main class="main-content">
473
+ <!-- Query Section -->
474
+ <section class="query-section">
475
+ <div class="query-body">
476
+ <textarea id="question" class="query-textarea"
477
+ placeholder="Ask a question about your data — e.g. “Which department has the highest average salary?” or “Show me sales by month as a chart.”"></textarea>
478
+
479
+ <div class="query-controls">
480
+ <select id="modeToggle" class="mode-select">
481
+ <option value="text2sql">Text-to-SQL</option>
482
+ <option value="ocr_qa">Document Q&amp;A</option>
483
+ </select>
484
+
485
+ <button id="ask" class="btn btn-primary">
486
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
487
+ stroke-width="2">
488
+ <path d="M12 19l7-7 3 3-7 7-3-3z" />
489
+ <path d="M18 13l-1.5-7.5L2 2l3.5 14.5L13 18l5-5z" />
490
+ </svg>
491
+ Ask
492
+ </button>
493
+
494
+ <button id="recalc" class="btn btn-secondary">
495
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
496
+ stroke-width="2">
497
+ <path d="M1 4v6h6" />
498
+ <path d="M23 20v-6h-6" />
499
+ <path
500
+ d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15" />
501
+ </svg>
502
+ Re-execute
503
+ </button>
504
+
505
+ <div id="uploadControls" class="hidden" style="display:flex; gap: 0.5rem; align-items: center;">
506
+ <button id="uploadBtn" class="btn btn-secondary">
507
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
508
+ stroke-width="2">
509
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
510
+ <polyline points="17,8 12,3 7,8" />
511
+ <line x1="12" y1="3" x2="12" y2="15" />
512
+ </svg>
513
+ Upload Image
514
+ </button>
515
+ <span id="uploadStatus">No document</span>
516
+ </div>
517
+
518
+ <div class="status-area">
519
+ <div id="spinner" class="spinner hidden"></div>
520
+ <span id="spinnerText" class="hidden">Thinking…</span>
521
+ <span id="status">Ready</span>
522
+ <span id="time"></span>
523
+ </div>
524
+ </div>
525
+ </div>
526
+ </section>
527
+
528
+ <!-- Results Grid -->
529
+ <div class="results-grid">
530
+ <!-- Main Results Column -->
531
+ <div class="main-results">
532
+ <!-- Answer Card -->
533
+ <div class="card">
534
+ <div class="card-header">
535
+ <h3 class="card-title">
536
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
537
+ stroke-width="2">
538
+ <path d="M9 11l3 3L22 4" />
539
+ <path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11" />
540
+ </svg>
541
+ Answer
542
+ </h3>
543
+ </div>
544
+ <div class="card-content">
545
+ <div id="answer" class="answer-content">No answer yet — ask something above.</div>
546
+ <div id="chartPending" class="chart-pending">
547
+ 📊 Charts &amp; analytics render here automatically when a successful query
548
+ returns chart-friendly data — try “Show average salary by department”.
549
+ </div>
550
+ <div id="chartBox" class="chart-box hidden">
551
+ <div id="chartCanvas"></div>
552
+ <p class="chart-caption" id="chartCaption"></p>
553
+ </div>
554
+ </div>
555
+ </div>
556
+
557
+ <!-- SQL Card -->
558
+ <div class="card">
559
+ <details id="sql-details" open>
560
+ <summary class="card-header">
561
+ <h3 class="card-title">
562
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor"
563
+ stroke-width="2">
564
+ <polyline points="16,18 22,12 16,6" />
565
+ <polyline points="8,6 2,12 8,18" />
566
+ </svg>
567
+ Generated SQL
568
+ </h3>
569
+ </summary>
570
+ <div class="card-content">
571
+ <pre
572
+ class="sql-content"><code id="sql" class="language-sql">-- SQL will appear here after the agent crafts a query --</code></pre>
573
+ </div>
574
+ </details>
575
+ </div>
576
+ </div>
577
+
578
+ <!-- Sidebar -->
579
+ <div class="agent-panels">
580
+ <!-- Database panel -->
581
+ <div class="panel">
582
+ <details open>
583
+ <summary class="panel-header">
584
+ <span class="panel-title">
585
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
586
+ stroke-width="2">
587
+ <ellipse cx="12" cy="5" rx="9" ry="3" />
588
+ <path d="M21 12c0 1.66-4 3-9 3s-9-1.34-9-3" />
589
+ <path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5" />
590
+ </svg>
591
+ Database
592
+ <span class="db-badge" id="dbBadge">—</span>
593
+ </span>
594
+ </summary>
595
+ <div class="profile-list" id="schemaProfiles"></div>
596
+ <div class="schema-add">
597
+ <label for="schemaName">Add a database</label>
598
+ <input type="text" id="schemaName" placeholder="Profile name (e.g. sales_2024)">
599
+ <label for="schemaUrl" style="margin-top:0.6rem">Connection URL — or upload a file</label>
600
+ <input type="text" id="schemaUrl"
601
+ placeholder="postgresql://user:pass@host/db · sqlite:///path/file.db">
602
+ <div class="row2">
603
+ <button id="schemaAddBtn" class="btn btn-primary">Connect</button>
604
+ <button id="schemaFileBtn" class="btn btn-secondary">Upload .sqlite / .csv</button>
605
+ </div>
606
+ </div>
607
+ <div class="schema-tables" id="schemaTables"></div>
608
+ </details>
609
+ </div>
610
+
611
+ <!-- Agent panels -->
612
+ <div class="panel">
613
+ <details open>
614
+ <summary class="panel-header">
615
+ <span class="panel-title">
616
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
617
+ stroke-width="2">
618
+ <path
619
+ d="M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22" />
620
+ </svg>
621
+ Memory Agent
622
+ </span>
623
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
624
+ stroke-width="2">
625
+ <polyline points="6,9 12,15 18,9" />
626
+ </svg>
627
+ </summary>
628
+ <div id="memory" class="panel-content">—</div>
629
+ </details>
630
+ </div>
631
+
632
+ <div class="panel">
633
+ <details open>
634
+ <summary class="panel-header">
635
+ <span class="panel-title">
636
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
637
+ stroke-width="2">
638
+ <path d="M12 20h9" />
639
+ <path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z" />
640
+ </svg>
641
+ Query Craft Agent
642
+ </span>
643
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
644
+ stroke-width="2">
645
+ <polyline points="6,9 12,15 18,9" />
646
+ </svg>
647
+ </summary>
648
+ <div id="querycraft" class="panel-content">—</div>
649
+ </details>
650
+ </div>
651
+
652
+ <div class="panel">
653
+ <details open>
654
+ <summary class="panel-header">
655
+ <span class="panel-title">
656
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
657
+ stroke-width="2">
658
+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
659
+ <polyline points="14,2 14,8 20,8" />
660
+ <line x1="16" y1="13" x2="8" y2="13" />
661
+ <line x1="16" y1="17" x2="8" y2="17" />
662
+ <polyline points="10,9 9,9 8,9" />
663
+ </svg>
664
+ Result Presenter Agent
665
+ </span>
666
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
667
+ stroke-width="2">
668
+ <polyline points="6,9 12,15 18,9" />
669
+ </svg>
670
+ </summary>
671
+ <div id="presenter" class="panel-content">—</div>
672
+ </details>
673
+ </div>
674
+ </div>
675
+ </div>
676
+ </main>
677
+
678
+ <!-- Footer -->
679
+ <footer class="footer">
680
+ <p>QueryLens — multi-agent Text-to-SQL &amp; document intelligence</p>
681
+ </footer>
682
+ </div>
683
+
684
+ <script src="https://cdn.jsdelivr.net/npm/echarts@5.5.0/dist/echarts.min.js"></script>
685
+ <script src="/static/app.js"></script>
686
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
687
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-sql.min.js"></script>
688
+ </body>
689
+
690
+ </html>
web/static/table-demo.html ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Table Demo</title>
7
+ <style>
8
+ /* Copy the same CSS variables and table styles from the main app */
9
+ :root {
10
+ --primary: #0f62fe;
11
+ --primary-hover: #0353e9;
12
+ --bg-primary: #FAFBFC;
13
+ --bg-secondary: #F4F6F8;
14
+ --bg-tertiary: #E8EDF3;
15
+ --card-bg: #ffffff;
16
+ --text-primary: #1A202C;
17
+ --text-secondary: #4A5568;
18
+ --text-tertiary: #718096;
19
+ --border: #D1D9E0;
20
+ --border-light: #E5EAF0;
21
+ --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
22
+ --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
23
+ --radius-sm: 0.25rem;
24
+ --radius-md: 0.375rem;
25
+ --radius-lg: 0.5rem;
26
+ --radius-xl: 0.75rem;
27
+ --space-1: 0.25rem;
28
+ --space-2: 0.5rem;
29
+ --space-3: 0.75rem;
30
+ --space-4: 1rem;
31
+ --space-6: 1.5rem;
32
+ --space-8: 2rem;
33
+ --space-12: 3rem;
34
+ --transition-normal: all 0.2s ease-in-out;
35
+ }
36
+
37
+ body {
38
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
39
+ background: var(--bg-secondary);
40
+ color: var(--text-primary);
41
+ margin: 2rem;
42
+ }
43
+
44
+ .table-wrapper {
45
+ position: relative;
46
+ margin: var(--space-4) 0;
47
+ border-radius: var(--radius-lg);
48
+ box-shadow: var(--shadow-lg);
49
+ background: var(--card-bg);
50
+ border: 1px solid var(--border);
51
+ overflow: hidden;
52
+ }
53
+
54
+ .table-controls {
55
+ display: flex;
56
+ align-items: center;
57
+ justify-content: space-between;
58
+ padding: var(--space-3) var(--space-4);
59
+ background: var(--bg-tertiary);
60
+ border-bottom: 1px solid var(--border);
61
+ gap: var(--space-3);
62
+ }
63
+
64
+ .table-controls-left {
65
+ display: flex;
66
+ align-items: center;
67
+ gap: var(--space-3);
68
+ }
69
+
70
+ .table-controls-right {
71
+ display: flex;
72
+ align-items: center;
73
+ gap: var(--space-2);
74
+ }
75
+
76
+ .table-info {
77
+ font-size: 0.875rem;
78
+ color: var(--text-secondary);
79
+ font-weight: 500;
80
+ }
81
+
82
+ .table-resize-controls {
83
+ display: flex;
84
+ align-items: center;
85
+ gap: var(--space-2);
86
+ }
87
+
88
+ .table-resize-btn {
89
+ padding: var(--space-1) var(--space-2);
90
+ border: 1px solid var(--border);
91
+ border-radius: var(--radius-sm);
92
+ background: var(--bg-primary);
93
+ color: var(--text-secondary);
94
+ font-size: 0.75rem;
95
+ cursor: pointer;
96
+ transition: var(--transition-normal);
97
+ }
98
+
99
+ .table-resize-btn:hover {
100
+ background: var(--bg-secondary);
101
+ color: var(--text-primary);
102
+ }
103
+
104
+ .table-resize-btn.active {
105
+ background: var(--primary);
106
+ color: white;
107
+ border-color: var(--primary);
108
+ }
109
+
110
+ .table-container {
111
+ overflow: auto;
112
+ max-height: 70vh;
113
+ position: relative;
114
+ }
115
+
116
+ .answer-table {
117
+ width: 100%;
118
+ border-collapse: separate;
119
+ border-spacing: 0;
120
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
121
+ font-size: 0.875rem;
122
+ background: var(--card-bg);
123
+ table-layout: auto;
124
+ min-width: 100%;
125
+ }
126
+
127
+ .answer-table.compact {
128
+ table-layout: fixed;
129
+ }
130
+
131
+ .answer-table.comfortable {
132
+ table-layout: auto;
133
+ }
134
+
135
+ .answer-table.spacious {
136
+ table-layout: auto;
137
+ font-size: 1rem;
138
+ }
139
+
140
+ .answer-table th,
141
+ .answer-table td {
142
+ padding: var(--space-3) var(--space-4);
143
+ text-align: left;
144
+ border-bottom: 1px solid var(--border-light);
145
+ border-right: 1px solid var(--border-light);
146
+ vertical-align: top;
147
+ position: relative;
148
+ }
149
+
150
+ .answer-table.compact th,
151
+ .answer-table.compact td {
152
+ padding: var(--space-2) var(--space-3);
153
+ max-width: 120px;
154
+ overflow: hidden;
155
+ text-overflow: ellipsis;
156
+ white-space: nowrap;
157
+ }
158
+
159
+ .answer-table.comfortable th,
160
+ .answer-table.comfortable td {
161
+ padding: var(--space-3) var(--space-4);
162
+ max-width: 200px;
163
+ word-wrap: break-word;
164
+ white-space: normal;
165
+ }
166
+
167
+ .answer-table.spacious th,
168
+ .answer-table.spacious td {
169
+ padding: var(--space-4) var(--space-6);
170
+ max-width: none;
171
+ word-wrap: break-word;
172
+ white-space: normal;
173
+ }
174
+
175
+ .answer-table th {
176
+ background: #F1F5F9;
177
+ font-weight: 600;
178
+ color: #1A202C;
179
+ position: sticky;
180
+ top: 0;
181
+ z-index: 10;
182
+ border-top: none;
183
+ border-bottom: 2px solid #D1D9E0;
184
+ }
185
+
186
+ .answer-table th:last-child,
187
+ .answer-table td:last-child {
188
+ border-right: none;
189
+ }
190
+
191
+ .answer-table tbody tr:hover {
192
+ background: #E8F4FD;
193
+ }
194
+
195
+ .answer-table tbody tr:nth-child(even) {
196
+ background: #F7F9FC;
197
+ }
198
+
199
+ .answer-table tbody tr:nth-child(even):hover {
200
+ background: #E8F4FD;
201
+ }
202
+ </style>
203
+ </head>
204
+ <body>
205
+ <h1>Enhanced Table Demo</h1>
206
+ <p>This demonstrates the new resizable table interface:</p>
207
+
208
+ <div class="table-wrapper">
209
+ <div class="table-controls">
210
+ <div class="table-controls-left">
211
+ <div class="table-info">9 rows × 7 columns</div>
212
+ </div>
213
+ <div class="table-controls-right">
214
+ <div class="table-resize-controls">
215
+ <button class="table-resize-btn" onclick="setTableSize('compact')">Compact</button>
216
+ <button class="table-resize-btn active" onclick="setTableSize('comfortable')">Comfortable</button>
217
+ <button class="table-resize-btn" onclick="setTableSize('spacious')">Spacious</button>
218
+ </div>
219
+ </div>
220
+ </div>
221
+ <div class="table-container">
222
+ <table class="answer-table comfortable">
223
+ <thead>
224
+ <tr>
225
+ <th>dept_name</th>
226
+ <th>avg_salary</th>
227
+ <th>num_employee</th>
228
+ <th>male_salary</th>
229
+ <th>female_salary</th>
230
+ <th>avg_male_salary</th>
231
+ <th>avg_female_salary</th>
232
+ </tr>
233
+ </thead>
234
+ <tbody>
235
+ <tr>
236
+ <td>Sales</td>
237
+ <td>$86,123.43</td>
238
+ <td>130</td>
239
+ <td>$6,181,954</td>
240
+ <td>$5,014,084</td>
241
+ <td>$84,684.37</td>
242
+ <td>$87,966.44</td>
243
+ </tr>
244
+ <tr>
245
+ <td>Marketing</td>
246
+ <td>$81,874.03</td>
247
+ <td>34</td>
248
+ <td>$1,736,164</td>
249
+ <td>$1,047,554</td>
250
+ <td>$82,674.38</td>
251
+ <td>$80,581.15</td>
252
+ </tr>
253
+ <tr>
254
+ <td>Finance</td>
255
+ <td>$76,399.98</td>
256
+ <td>43</td>
257
+ <td>$2,026,534</td>
258
+ <td>$1,258,664</td>
259
+ <td>$75,056.70</td>
260
+ <td>$78,666.75</td>
261
+ </tr>
262
+ <tr>
263
+ <td>Development</td>
264
+ <td>$69,564.44</td>
265
+ <td>203</td>
266
+ <td>$8,159,084</td>
267
+ <td>$5,962,504</td>
268
+ <td>$69,735.73</td>
269
+ <td>$69,331.42</td>
270
+ </tr>
271
+ <tr>
272
+ <td>Research</td>
273
+ <td>$69,147.39</td>
274
+ <td>51</td>
275
+ <td>$2,279,864</td>
276
+ <td>$1,246,654</td>
277
+ <td>$69,086.76</td>
278
+ <td>$69,258.56</td>
279
+ </tr>
280
+ <tr>
281
+ <td>Production</td>
282
+ <td>$68,537.28</td>
283
+ <td>186</td>
284
+ <td>$7,929,244</td>
285
+ <td>$4,818,694</td>
286
+ <td>$68,355.55</td>
287
+ <td>$68,838.43</td>
288
+ </tr>
289
+ <tr>
290
+ <td>Quality Management</td>
291
+ <td>$64,859.40</td>
292
+ <td>48</td>
293
+ <td>$2,112,644</td>
294
+ <td>$1,000,604</td>
295
+ <td>$64,019.61</td>
296
+ <td>$66,706.93</td>
297
+ </tr>
298
+ <tr>
299
+ <td>Customer Service</td>
300
+ <td>$63,643.00</td>
301
+ <td>61</td>
302
+ <td>$1,730,834</td>
303
+ <td>$2,151,394</td>
304
+ <td>$61,815.43</td>
305
+ <td>$65,193.67</td>
306
+ </tr>
307
+ <tr>
308
+ <td>Human Resources</td>
309
+ <td>$63,507.28</td>
310
+ <td>46</td>
311
+ <td>$2,151,834</td>
312
+ <td>$769,499</td>
313
+ <td>$63,289.29</td>
314
+ <td>$64,124.92</td>
315
+ </tr>
316
+ </tbody>
317
+ </table>
318
+ </div>
319
+ </div>
320
+
321
+ <script>
322
+ function setTableSize(size) {
323
+ const table = document.querySelector('.answer-table');
324
+ const buttons = document.querySelectorAll('.table-resize-btn');
325
+
326
+ // Remove all size classes
327
+ table.classList.remove('compact', 'comfortable', 'spacious');
328
+
329
+ // Add selected size class
330
+ table.classList.add(size);
331
+
332
+ // Update active button
333
+ buttons.forEach(btn => btn.classList.remove('active'));
334
+ event.target.classList.add('active');
335
+ }
336
+ </script>
337
+ </body>
338
+ </html>