-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3269 lines (2788 loc) · 137 KB
/
app.py
File metadata and controls
3269 lines (2788 loc) · 137 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import pandas as pd
import glob
import tempfile
import sounddevice as sd
import soundfile as sf
import time
import numpy as np
import base64
import hashlib
from flask import Flask, request, jsonify, render_template, send_file, Response, stream_with_context
from talk2sql.engine import Talk2SQLAzure
# from talk2sql.engine import Talk2SQL_anthropic
from talk2sql.utils import format_sql_with_xml_tags, extract_content_from_xml_tags
import groq
import threading
import sqlite3
import logging
import datetime
import io
import csv
import zipfile
import statistics
import traceback
import uuid
from collections import Counter, defaultdict
import re
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
print("Warning: python-dotenv not installed. Install with 'pip install python-dotenv' to load environment variables from .env file")
app = Flask(__name__)
DB_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'databases')
# Initialize Talk2SQLAzure with Azure OpenAI
config = {
# "anthropic_api_key": os.environ.get("ANTHROPIC_API_KEY"),
# "claude_model": os.environ.get("CLAUDE_MODEL", "claude-3-5-haiku-20241022"),
# "temperature": 0.3,
# "enable_thinking": False,
# "thinking_budget_tokens": 2000,
"azure_api_key": os.environ.get("AZURE_OPENAI_API_KEY"),
"azure_endpoint": os.environ.get("AZURE_ENDPOINT"),
"azure_api_version": os.environ.get("AZURE_API_VERSION", "2024-02-15-preview"),
"azure_deployment": os.environ.get("AZURE_DEPLOYMENT", "gpt-4o-mini"),
"azure_embedding_deployment": "text-embedding-ada-002",
"temperature": 0.3,
# Vector store settings - Use Qdrant Cloud if credentials are available
"qdrant_url": os.environ.get("QDRANT_URL"), # URL for Qdrant Cloud
"qdrant_api_key": os.environ.get("QDRANT_API_KEY"), # API key for Qdrant Cloud
"prefer_grpc": True, # Use gRPC for better performance
# Retry settings
"max_retry_attempts": 3,
"save_query_history": True,
"history_db_path": os.path.join(DB_FOLDER, "query_history.sqlite"), # Store query history in databases folder
# General settings
"debug_mode": True,
}
# If we have a Qdrant URL and API key, switch to persistent vector store
using_persistent_vectors = (config.get("qdrant_url") is not None and config.get("qdrant_api_key") is not None)
if using_persistent_vectors:
print(f"Using persistent vector storage at {config['qdrant_url']}")
else:
print("Using in-memory vector storage - embeddings will be lost when app restarts")
# Initialize Talk2SQL
Talk2SQL = Talk2SQLAzure(config)
# Talk2SQL = Talk2SQLAnthropic(config)
# Ensure query history saving is enabled
if not Talk2SQL.save_query_history:
print("Enabling query history saving")
Talk2SQL.save_query_history = True
# Log the query history database path
query_history_path = getattr(Talk2SQL, "history_db_path", config.get("history_db_path", "default location"))
print(f"Query history is being saved to: {query_history_path}")
print(f"Absolute path to query history: {os.path.abspath(query_history_path)}")
print(f"Database folder path: {DB_FOLDER}")
print(f"Database folder exists: {os.path.exists(DB_FOLDER)}")
# Ensure the path is set as an attribute if it's not already
if not hasattr(Talk2SQL, "history_db_path"):
Talk2SQL.history_db_path = config.get("history_db_path")
print(f"Setting history_db_path attribute to: {Talk2SQL.history_db_path}")
# Initialize Groq client for speech capabilities (optional - only needed for voice features)
groq_api_key = os.environ.get("GROQ_API_KEY")
if groq_api_key:
groq_client = groq.Groq(api_key=groq_api_key)
print("Groq client initialized for voice features")
else:
groq_client = None
print("Groq API key not found - voice features will be disabled")
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
# Constants
TRAINING_DATA_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'training_data')
AUDIO_FOLDER = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'audio_cache')
# Configure Flask app
app.config['UPLOAD_FOLDER'] = AUDIO_FOLDER
# Ensure directories exist
os.makedirs(DB_FOLDER, exist_ok=True)
os.makedirs(TRAINING_DATA_FOLDER, exist_ok=True)
os.makedirs(AUDIO_FOLDER, exist_ok=True)
print(f"Created or verified database folder at: {DB_FOLDER}")
print(f"Expected query history location: {os.path.join(DB_FOLDER, 'query_history.sqlit')}")
# Store the current database path
current_db_path = None
current_db_name = None
db_collection_created = {} # Keep track of which databases have collections
# Thread-safe SQLite connection
_thread_local = threading.local()
def get_thread_safe_connection():
"""
Gets a thread-safe connection to the current database.
If there's no connection for the current thread, creates one.
"""
thread_id = threading.get_ident()
if not hasattr(_thread_local, 'connection'):
logging.info(f"Creating new connection for thread {thread_id}")
if app.config.get('DATABASE_PATH'):
# Create a new connection with check_same_thread=False for this thread
db_path = app.config.get('DATABASE_PATH')
_thread_local.connection = sqlite3.connect(db_path, check_same_thread=False)
logging.info(f"Created new SQLite connection for thread {thread_id}")
else:
logging.warning(f"No database selected for thread {thread_id}")
return _thread_local.connection if hasattr(_thread_local, 'connection') else None
# Generate deterministic collection name for a database
def get_collection_name_for_db(db_path):
# Create a hash of the database path
db_hash = hashlib.md5(db_path.encode()).hexdigest()[:8]
base_name = os.path.basename(db_path).replace('.', '_').replace('-', '_')
# Combine the base name and hash for a unique but recognizable name
return f"{base_name}_{db_hash}"
# Connect to a selected database
@app.route('/connect', methods=['POST'])
def connect_to_database():
global current_db_path, current_db_name, db_collection_created, _thread_local
db_path = request.json.get('db_path')
# If no path provided, list available databases
if not db_path:
return jsonify({
"status": "error",
"message": "No database path provided"
})
try:
# Print some debug info
print(f"Attempting to connect to database at: {db_path}")
print(f"File exists: {os.path.exists(db_path)}")
if os.path.exists(db_path):
print(f"File size: {os.path.getsize(db_path)} bytes")
# First connect to the database to ensure we can access it
Talk2SQL.connect_to_sqlite(db_path)
current_db_path = db_path
current_db_name = os.path.basename(db_path)
# Store the database path in app configuration for thread-safe access
app.config['DATABASE_PATH'] = db_path
# Reset thread-local storage since we're connecting to a new database
# This ensures each thread will create a new connection to the new database
if hasattr(_thread_local, 'connection'):
# Close existing connection if it exists
try:
_thread_local.connection.close()
except:
pass
_thread_local.connection = None
# Create a connection for the main thread
conn = sqlite3.connect(db_path, check_same_thread=False)
_thread_local.connection = conn
logging.info(f"Created thread-safe connection for main thread: {threading.get_ident()}")
# Check if we've already created a collection for this database
collections_exist = False
if using_persistent_vectors:
# Get the collection name for this database
collection_name = get_collection_name_for_db(db_path)
# Set the collection names for this database
Talk2SQL.questions_collection = f"{collection_name}_questions"
Talk2SQL.schema_collection = f"{collection_name}_schema"
Talk2SQL.docs_collection = f"{collection_name}_docs"
# Check if we've already created these collections and they have data
if db_collection_created.get(db_path, False):
print(f"Using existing collections for {db_path}")
collections_exist = True
else:
try:
# Check if collections exist and have data
exists_and_has_data = False
try:
# Try to count records in the questions collection
count = Talk2SQL.qdrant_client.count(
collection_name=Talk2SQL.questions_collection
).count
exists_and_has_data = count > 0
if exists_and_has_data:
print(f"Found existing collection with {count} examples")
except Exception as e:
print(f"Collection doesn't exist yet or error checking: {e}")
if not exists_and_has_data:
# Create collections if they don't exist or are empty
Talk2SQL._setup_collections()
print(f"Created vector collections for {db_path}")
else:
print(f"Using existing collections with data for {db_path}")
collections_exist = True
db_collection_created[db_path] = True
except Exception as e:
print(f"Error creating collections: {e}")
# Load database schema - only if we haven't created this collection before
# or if we're not using persistent vectors
schema = ""
if not using_persistent_vectors or not collections_exist:
schema = get_db_schema()
if schema:
print(f"Loaded database schema: {len(schema)} characters")
else:
print("Warning: No schema loaded")
else:
print("Using existing schema from vector store")
# Load training examples for this database - only if needed
# or if we're not using persistent vectors
examples_loaded = False
if not using_persistent_vectors or not collections_exist:
examples_loaded = load_training_examples()
if examples_loaded:
print("Successfully loaded training examples")
else:
print("Warning: Failed to load training examples")
else:
examples_loaded = True
print("Using existing training examples from vector store")
# Generate starter questions when connecting to a database
starter_questions = []
if schema:
try:
# Generate 5 starter questions based on the schema
starter_questions = Talk2SQL.generate_starter_questions(schema, 5)
print(f"Generated {len(starter_questions)} starter questions")
except Exception as e:
print(f"Error generating starter questions: {e}")
# Don't let this error prevent connection
return jsonify({
"status": "success",
"message": f"Connected to {db_path}",
"schema_loaded": bool(schema) or collections_exist,
"examples_loaded": examples_loaded,
"db_name": current_db_name,
"using_persistent_vectors": using_persistent_vectors,
"thread_safe": True,
"starter_questions": starter_questions
})
except Exception as e:
print(f"Error connecting to database: {str(e)}")
import traceback
traceback.print_exc()
return jsonify({"status": "error", "message": str(e)})
# Get a list of available databases
@app.route('/databases', methods=['GET'])
def list_databases():
try:
# List all .sqlite files in the databases folder
db_files = glob.glob(os.path.join(DB_FOLDER, '*.sqlite'))
db_files.extend(glob.glob(os.path.join(DB_FOLDER, '*.db')))
# Log the found databases
print(f"Found database files: {db_files}")
# Format for frontend
databases = []
for db_file in db_files:
db_name = os.path.basename(db_file)
# Check if we have a persisted collection for this database
has_persisted = False
if using_persistent_vectors:
has_persisted = db_collection_created.get(db_file, False)
# Check if this is the query history database
query_history_path = getattr(Talk2SQL, "history_db_path", config.get("history_db_path", ""))
is_query_history = db_file == query_history_path
databases.append({
'name': db_name,
'path': db_file,
'has_persisted_vectors': has_persisted,
'is_query_history': is_query_history
})
# Also check if the default NBA database exists
default_path = '/Users/kabeerthockchom/Desktop/Talk2SQL/Talk2SQL/nba.sqlite'
if os.path.exists(default_path) and default_path not in [db['path'] for db in databases]:
databases.append({
'name': 'nba.sqlite (default)',
'path': default_path,
'has_persisted_vectors': False,
'is_query_history': False
})
return jsonify({
"status": "success",
"databases": databases,
"current_db": current_db_name,
"using_persistent_vectors": using_persistent_vectors
})
except Exception as e:
print(f"Error listing databases: {e}")
return jsonify({"status": "error", "message": str(e)})
# Get Qdrant vector store status (for admin purposes)
@app.route('/vector_store_status', methods=['GET'])
def vector_store_status():
try:
if not using_persistent_vectors:
return jsonify({
"status": "success",
"vector_store": "in-memory",
"message": "Using in-memory vector storage"
})
# Get list of collections
collections = Talk2SQL.qdrant_client.get_collections().collections
collection_names = [c.name for c in collections]
# Get counts for current database collections
counts = {}
if current_db_path:
collection_name = get_collection_name_for_db(current_db_path)
for coll_type in ["questions", "schema", "docs"]:
full_name = f"{collection_name}_{coll_type}"
if full_name in collection_names:
try:
count = Talk2SQL.qdrant_client.count(
collection_name=full_name
).count
counts[coll_type] = count
except:
counts[coll_type] = "error"
return jsonify({
"status": "success",
"vector_store": "persistent",
"url": config["location"],
"collections": collection_names,
"current_db_collections": counts if current_db_path else None
})
except Exception as e:
print(f"Error getting vector store status: {e}")
return jsonify({"status": "error", "message": str(e)})
# Check query history database status
@app.route('/query_history_status', methods=['GET'])
def query_history_status():
try:
query_history_path = getattr(Talk2SQL, "history_db_path", config.get("history_db_path", "unknown"))
exists = os.path.exists(query_history_path) if isinstance(query_history_path, str) else False
print(f"Checking query history status: {query_history_path}")
print(f"File exists: {exists}")
# If the file exists, get some basic info
file_info = {}
if exists:
file_info["size_bytes"] = os.path.getsize(query_history_path)
file_info["created"] = datetime.datetime.fromtimestamp(os.path.getctime(query_history_path)).isoformat()
file_info["modified"] = datetime.datetime.fromtimestamp(os.path.getmtime(query_history_path)).isoformat()
# Try to get query count
try:
history = Talk2SQL.get_query_history(limit=None)
# Make sure data is serializable before storing in file_info
serializable_history = []
for item in history:
# Convert any bytes objects in each history item
for key, value in list(item.items()):
if isinstance(value, bytes):
try:
# Convert bytes to base64 string
import base64
item[key] = base64.b64encode(value).decode('utf-8')
except:
# If conversion fails, remove the key
item[key] = None
serializable_history.append(item)
file_info["query_count"] = len(serializable_history) if serializable_history else 0
print(f"Found {file_info['query_count']} queries in history database")
except Exception as e:
file_info["query_count_error"] = str(e)
print(f"Error getting query count: {e}")
import traceback
traceback.print_exc()
return jsonify({
"status": "success",
"query_history_path": query_history_path,
"exists": exists,
"in_databases_folder": query_history_path.startswith(DB_FOLDER) if isinstance(query_history_path, str) else False,
"file_info": file_info if exists else None
})
except Exception as e:
print(f"Error checking query history status: {e}")
import traceback
traceback.print_exc()
return jsonify({"status": "error", "message": str(e)})
# Upload a new database file
@app.route('/upload_database', methods=['POST'])
def upload_database():
if 'file' not in request.files:
return jsonify({"status": "error", "message": "No file uploaded"})
file = request.files['file']
if file.filename == '':
return jsonify({"status": "error", "message": "No file selected"})
if not (file.filename.endswith('.sqlite') or file.filename.endswith('.db')):
return jsonify({"status": "error", "message": "Only .sqlite or .db files are allowed"})
try:
# Save the file to the databases folder
file_path = os.path.join(DB_FOLDER, file.filename)
file.save(file_path)
return jsonify({
"status": "success",
"message": f"Database {file.filename} uploaded successfully",
"path": file_path
})
except Exception as e:
print(f"Error uploading database: {e}")
return jsonify({"status": "error", "message": str(e)})
# Upload training data file
@app.route('/upload_training_data', methods=['POST'])
def upload_training_data():
if 'file' not in request.files:
return jsonify({"status": "error", "message": "No file uploaded"})
file = request.files['file']
if file.filename == '':
return jsonify({"status": "error", "message": "No file selected"})
if not file.filename.endswith('.json'):
return jsonify({"status": "error", "message": "Only .json files are allowed"})
try:
# Save the file to the training_data folder with a name related to the current DB
if current_db_name:
base_name = os.path.splitext(current_db_name)[0]
file_path = os.path.join(TRAINING_DATA_FOLDER, f"{base_name}_training.json")
else:
file_path = os.path.join(TRAINING_DATA_FOLDER, file.filename)
file.save(file_path)
# Load the training data immediately
examples_loaded = load_training_examples()
# If using persistent vectors, mark this database as having vectors
if using_persistent_vectors and current_db_path:
db_collection_created[current_db_path] = True
return jsonify({
"status": "success",
"message": f"Training data {file.filename} uploaded successfully",
"examples_loaded": examples_loaded,
"path": file_path
})
except Exception as e:
print(f"Error uploading training data: {e}")
return jsonify({"status": "error", "message": str(e)})
# Load training examples from all relevant sources
def load_training_examples():
try:
# Try to load from database-specific training data file first
examples_loaded = False
loaded_count = 0
# If we have a current database, look for a database-specific training file
if current_db_name:
base_name = os.path.splitext(current_db_name)[0]
db_specific_path = os.path.join(TRAINING_DATA_FOLDER, f"{base_name}_training.json")
if os.path.exists(db_specific_path):
print(f"Loading database-specific training examples from: {db_specific_path}")
examples_loaded, count = load_training_file(db_specific_path)
loaded_count += count
if examples_loaded:
print(f"Loaded {count} database-specific examples into vector store")
# Also load user feedback for this database
if current_db_name:
user_feedback_path = os.path.join(TRAINING_DATA_FOLDER, f"{base_name}_feedback.json")
if os.path.exists(user_feedback_path):
print(f"Loading user feedback examples from: {user_feedback_path}")
feedback_loaded, count = load_training_file(user_feedback_path)
examples_loaded = feedback_loaded or examples_loaded
loaded_count += count
if feedback_loaded:
print(f"Loaded {count} user feedback examples into vector store")
# If no database-specific file, try the default one
if not examples_loaded:
# Look in the current directory first
default_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'ground_truth_data.json')
if os.path.exists(default_path):
print(f"Loading default training examples from: {default_path}")
default_loaded, count = load_training_file(default_path)
examples_loaded = default_loaded
loaded_count += count
if default_loaded:
print(f"Loaded {count} default examples into vector store")
if examples_loaded and using_persistent_vectors:
print(f"Total of {loaded_count} examples stored in persistent vector database")
return examples_loaded
except Exception as e:
print(f"Error loading training examples: {e}")
import traceback
traceback.print_exc()
return False
# Load training examples from a specific file
def load_training_file(file_path):
try:
print(f"Loading training examples from: {file_path}")
with open(file_path, 'r') as f:
data = json.load(f)
# Add examples to Talk2SQL
added_count = 0
for example in data:
question = example['natural_language']
sql = example['sql']
# Format SQL with XML tags for storage
formatted_sql = format_sql_with_xml_tags(sql)
# Add to Talk2SQL
try:
# Extract the SQL without tags for adding to the database
Talk2SQL.add_question_sql(question, sql)
added_count += 1
except Exception as e:
print(f"Error adding example: {question}, error: {e}")
continue
print(f"Added {added_count} of {len(data)} training examples")
return added_count > 0, added_count
except Exception as e:
print(f"Error loading training file {file_path}: {e}")
import traceback
traceback.print_exc()
return False, 0
# Record user feedback (thumbs up/down)
@app.route('/feedback', methods=['POST'])
def record_feedback():
feedback = request.json.get('feedback', '')
question = request.json.get('question', '')
sql = request.json.get('sql', '')
if not question or not sql or feedback not in ['up', 'down']:
return jsonify({"status": "error", "message": "Invalid feedback data"})
try:
# For thumbs up, add the example to the database-specific feedback file
if feedback == 'up' and current_db_name:
base_name = os.path.splitext(current_db_name)[0]
feedback_path = os.path.join(TRAINING_DATA_FOLDER, f"{base_name}_feedback.json")
# Create or load existing feedback file
examples = []
if os.path.exists(feedback_path):
with open(feedback_path, 'r') as f:
examples = json.load(f)
# Check for duplicates before adding
is_duplicate = False
for example in examples:
# Check if the same question and SQL already exist
if example.get('natural_language') == question and example.get('sql') == sql:
is_duplicate = True
break
if is_duplicate:
print(f"Duplicate entry found, not adding to feedback: {question}")
return jsonify({
"status": "success",
"message": "This example is already in the training data",
"feedback": feedback,
"duplicate": True
})
# Add new example
examples.append({
"natural_language": question,
"sql": sql,
"type": "user_feedback"
})
# Save updated file
with open(feedback_path, 'w') as f:
json.dump(examples, f, indent=2)
# Also add to Talk2SQL immediately
try:
Talk2SQL.add_question_sql(question, sql)
print(f"Added feedback example to vector store: {question}")
# Update persistent storage tracking if using Qdrant
if using_persistent_vectors and current_db_path:
db_collection_created[current_db_path] = True
return jsonify({
"status": "success",
"message": "Feedback recorded and added to training examples",
"feedback": feedback,
"stored_in_vectors": True
})
except Exception as e:
print(f"Error adding feedback to vector store: {e}")
return jsonify({
"status": "success",
"message": "Feedback recorded in file but not added to vector store",
"feedback": feedback,
"stored_in_vectors": False,
"error": str(e)
})
else:
return jsonify({
"status": "success",
"message": "Feedback recorded",
"feedback": feedback
})
except Exception as e:
print(f"Error recording feedback: {e}")
return jsonify({"status": "error", "message": str(e)})
# Clean up duplicate entries from feedback and training files
@app.route('/cleanup_duplicates', methods=['POST'])
def cleanup_duplicates():
try:
duplicates_removed = 0
files_cleaned = 0
# Find all JSON files in the training data folder
training_files = glob.glob(os.path.join(TRAINING_DATA_FOLDER, '*.json'))
for file_path in training_files:
try:
with open(file_path, 'r') as f:
examples = json.load(f)
# Track unique examples by question + SQL combination
unique_examples = []
seen_pairs = set()
for example in examples:
question = example.get('natural_language', '')
sql = example.get('sql', '')
# Create a key for this example
example_key = f"{question}::{sql}"
# Add only if not seen before
if example_key not in seen_pairs:
seen_pairs.add(example_key)
unique_examples.append(example)
else:
duplicates_removed += 1
# Only write back if duplicates were found
if len(unique_examples) < len(examples):
with open(file_path, 'w') as f:
json.dump(unique_examples, f, indent=2)
files_cleaned += 1
print(f"Cleaned {len(examples) - len(unique_examples)} duplicates from {file_path}")
except Exception as e:
print(f"Error processing {file_path}: {e}")
# Re-load training examples if duplicates were removed
if duplicates_removed > 0:
load_training_examples()
return jsonify({
"status": "success",
"message": f"Removed {duplicates_removed} duplicate entries from {files_cleaned} files",
"duplicates_removed": duplicates_removed,
"files_cleaned": files_cleaned
})
except Exception as e:
print(f"Error cleaning up duplicates: {e}")
return jsonify({"status": "error", "message": str(e)})
# Get schema information from the database
def get_db_schema():
try:
print("Attempting to extract database schema...")
# First, verify database connection
try:
test_df = Talk2SQL.run_sql("SELECT 1")
print(f"Database connection test: {not test_df.empty}")
except Exception as e:
print(f"Database connection test failed: {e}")
return ""
# Get all tables using a more robust query
print("Querying for tables...")
tables_df = Talk2SQL.run_sql("""
SELECT name
FROM sqlite_master
WHERE type='table' AND name NOT LIKE 'sqlite_%'
""")
print(f"Tables found: {len(tables_df) if not tables_df.empty else 0}")
if not tables_df.empty:
print(f"Table names: {', '.join(tables_df['name'].tolist())}")
if tables_df.empty:
print("No tables found in database - checking if database file exists and has content")
# This could indicate an issue with the database file
return ""
schema_definitions = []
table_count = 0
# Get create statements for each table
for table in tables_df['name']:
print(f"Processing table: {table}")
try:
create_stmt_df = Talk2SQL.run_sql(f"SELECT sql FROM sqlite_master WHERE name='{table}'")
if not create_stmt_df.empty and create_stmt_df['sql'][0] is not None:
schema_definitions.append(create_stmt_df['sql'][0])
# Also get a sample of the data to better understand the schema
sample_df = Talk2SQL.run_sql(f"SELECT * FROM {table} LIMIT 1")
columns = list(sample_df.columns)
schema_definitions.append(f"-- Table {table} columns: {', '.join(columns)}")
# Add column descriptions (simplified to avoid potential errors)
column_info = []
for col in columns:
try:
# Only get distinct values for columns (simpler approach)
distinct_df = Talk2SQL.run_sql(f"SELECT COUNT(DISTINCT {col}) FROM {table}")
if not distinct_df.empty and distinct_df.iloc[0, 0] < 10:
values_df = Talk2SQL.run_sql(f"SELECT DISTINCT {col} FROM {table} LIMIT 10")
values = values_df[values_df.columns[0]].tolist()
column_info.append(f"-- Column {col} possible values: {', '.join(map(str, values))}")
except Exception as e:
print(f"Error getting column stats for {table}.{col}: {e}")
schema_definitions.extend(column_info)
table_count += 1
except Exception as e:
print(f"Error getting schema for table {table}: {e}")
print(f"Extracted schema for {table_count} tables")
# Join all schema definitions
full_schema = '\n\n'.join(schema_definitions)
# Add schema to Talk2SQL
if full_schema:
Talk2SQL.add_schema(full_schema)
# Add a more readable description
description = f"""
This is a database with {table_count} tables.
"""
Talk2SQL.add_documentation(description)
return full_schema
except Exception as e:
print(f"Error getting schema: {e}")
import traceback
traceback.print_exc()
return ""
# Ask question to Talk2SQL
@app.route('/ask', methods=['POST'])
def ask_question():
try:
# Get the question, database ID, and visualization flag
question = request.json.get('question')
db_id = request.json.get('db_id', request.json.get('database'))
visualize = request.json.get('visualize', True)
# Check if we should save the query to history
save_query = request.json.get('save_query', True)
original_save_query = Talk2SQL.save_query_history
if not save_query:
Talk2SQL.save_query_history = False
# Ensure database connection
get_thread_safe_connection()
# Execute the query
result = Talk2SQL.smart_query(question, print_results=False, visualize=visualize)
# Restore save_query_history setting
Talk2SQL.save_query_history = original_save_query
# Prepare the response
response = {
"status": "success" if result["success"] else "error",
"sql": result["sql"],
"retry_count": result.get("retry_count", 0),
"question": question,
"used_memory": result.get("used_memory", False) # Include memory usage
}
# Add timing information if available
if "timing" in result:
response["timing"] = result["timing"]
if result["success"]:
# If successful, include data and visualization
df = result["data"]
if df is not None:
response["data"] = df.to_dict(orient='records')
response["columns"] = df.columns.tolist()
# The summary is already generated in smart_query and stored in the result
if "summary" in result:
response["summary"] = result["summary"]
# Include visualization if available
if result["visualization"] is not None:
try:
response["visualization"] = result["visualization"].to_json()
except Exception as e:
print(f"Error converting visualization to JSON: {e}")
else:
# If error, include the error message
response["error"] = result.get("error", "Unknown error")
# Include the corrected SQL if available
if "corrected_sql" in result:
response["corrected_sql"] = result["corrected_sql"]
return jsonify(response)
except Exception as e:
print(f"Error processing question: {e}")
import traceback
traceback.print_exc()
return jsonify({"status": "error", "error": str(e)})
# Generate follow-up questions
@app.route('/follow_up_questions', methods=['POST'])
def follow_up_questions_endpoint():
question = request.json.get('question', '')
sql = request.json.get('sql', '')
result_info = request.json.get('result_info', '')
n = request.json.get('n', 3)
if not question or not sql:
return jsonify({"status": "error", "message": "Question and SQL query are required"})
try:
# Call the generate_follow_up_questions method
followups = Talk2SQL.generate_follow_up_questions(
question=question,
sql=sql,
result_info=result_info,
n=n
)
return jsonify({
"status": "success",
"question": question,
"followup_questions": followups
})
except Exception as e:
print(f"Error generating follow-up questions: {e}")
import traceback
traceback.print_exc()
return jsonify({"status": "error", "message": str(e)})
# Generate a summary of the data using Azure OpenAI
def generate_data_summary(question, result):
try:
# Start timing
summary_start_time = datetime.datetime.now()
# Create a prompt for OpenAI to summarize the data
prompt = f"""
The user asked: "{question}"
I ran the following SQL query:
{result["sql"]}
The query returned a dataframe with {len(result["data"])} rows and {len(result["data"].columns)} columns.
Column names: {', '.join(result["data"].columns)}
Here's a sample of the data:
{result["data"].head(5).to_string()}
Please provide a clear, concise summary of this data that directly answers the user's question, citing the tables and columns used to answer the question.
Do not repeat the data, just summarize it.
Include key insights, trends, or patterns if relevant. Keep it brief and focused.
Example of your task:
Question: How many teams are in the NBA?
SQL: SELECT t.full_name, ROUND(AVG(gi.attendance), 0) as avg_attendance
FROM game g
JOIN game_info gi ON g.game_id = gi.game_id
JOIN team t ON g.team_id_home = t.id
WHERE gi.attendance > 0
GROUP BY t.id, t.full_name
ORDER BY avg_attendance DESC
LIMIT 1
Data:full_name avg_attendance
18622 Toronto Raptors
Assistant:
The Toronto Raptors have the highest average attendance in the NBA with 18,622 fans per game, this was inferred using the table game_info and the column attendance.
"""
# Create the messages for the prompt
messages = [
{"role": "system", "content": "You are a helpful AI that summarizes data and answers questions."},
{"role": "user", "content": prompt}
]
# Use Talk2SQL's client (Anthropic client uses claude_model)
response = Talk2SQL.client.chat.completions.create(
# model=config["claude_model"],
model="gpt-4o-mini",
messages=messages,
temperature=0.3,
max_tokens=400
)
summary = response.choices[0].message.content
summary_end_time = datetime.datetime.now()
summary_time_ms = (summary_end_time - summary_start_time).total_seconds() * 1000
# Get recent history and update with summary
recent_history = Talk2SQL.get_query_history(successful_only=True, limit=10)
for entry in recent_history:
if entry.get("question") == question and "summary" not in entry:
# Re-record the query attempt with the summary added
Talk2SQL.record_query_attempt(
question=entry.get("question"),
sql=entry.get("sql"),
success=True,
retry_count=entry.get("retry_count", 0),
data=entry.get("data"),
columns=entry.get("columns"),
visualization=entry.get("visualization"),
summary=summary,
explanation_time_ms=summary_time_ms