File size: 18,592 Bytes
9f9844d
 
 
 
af1fee3
9f9844d
 
 
 
 
 
 
 
 
 
 
 
 
10613ff
 
 
 
35b0fd8
6134c15
10613ff
 
9f9844d
 
 
 
 
 
 
 
 
6d149f9
9f9844d
 
 
 
 
 
 
6d149f9
 
 
 
 
 
 
 
9f9844d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d149f9
9f9844d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af1fee3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9844d
 
 
 
6d149f9
9f9844d
 
 
 
 
 
 
6d149f9
 
9f9844d
 
 
 
 
 
 
 
 
 
 
a2e9487
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9844d
 
 
 
a2e9487
 
 
 
 
9f9844d
 
 
4380c2b
 
 
 
 
 
9f9844d
 
 
 
 
 
 
 
 
6d149f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9844d
6d149f9
9f9844d
6d149f9
 
9f9844d
 
a2e9487
 
 
 
 
 
 
9f9844d
 
 
6d149f9
9f9844d
6d149f9
 
9f9844d
 
af1fee3
 
 
 
 
 
9f9844d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4380c2b
9f9844d
4380c2b
 
9f9844d
4380c2b
 
 
 
 
 
6d149f9
 
 
 
 
4380c2b
6d149f9
 
 
 
 
 
 
9f9844d
6d149f9
 
 
 
 
 
9f9844d
 
 
 
 
6d149f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9844d
6d149f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f9844d
6d149f9
9f9844d
6d149f9
 
 
 
 
 
 
 
9f9844d
 
6d149f9
 
 
 
 
 
 
 
 
 
 
 
9f9844d
 
6d149f9
9f9844d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import os
import pandas as pd
from typing import Literal, TypedDict
from sqlalchemy import create_engine, inspect, text
from transformers import AutoTokenizer
from utils import pprint
import time
import re

from openai import OpenAI
import anthropic
from clients.openRouter import OpenRouter

# Load environment variables
from dotenv import load_dotenv
load_dotenv()

# Set up page configuration
st.set_page_config(
    page_title="SQL Query Assistant",
    page_icon="💾",
    layout="centered",
    initial_sidebar_state="collapsed"
)

ModelType = Literal["GPT_4o", "GPT_o1", "CLAUDE", "LLAMA", "DEEPSEEK", "DEEPSEEK_R1", "DEEPSEEK_R1_DISTILL"]
ModelConfig = TypedDict("ModelConfig", {
    "client": OpenAI | anthropic.Anthropic,
    "model": str,
    "max_context": int,
    "tokenizer": AutoTokenizer
})

MODEL_CONFIG: dict[ModelType, ModelConfig] = {
    "CLAUDE_HAIKU": {
        "client": anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY")),
        "model": "claude-3-5-haiku-20241022",
        # "model": "claude-3-5-sonnet-20241022",
        # "model": "claude-3-5-sonnet-20240620",
        "max_context": 40000,
        "tokenizer": AutoTokenizer.from_pretrained("Xenova/claude-tokenizer")
    },
    "CLAUDE_SONNET": {
        "client": anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY")),
        # "model": "claude-3-5-haiku-20241022",
        # "model": "claude-3-5-sonnet-20241022",
        "model": "claude-3-5-sonnet-20240620",
        "max_context": 40000,
        "tokenizer": AutoTokenizer.from_pretrained("Xenova/claude-tokenizer")
    },
    "GPT_4o": {
        "client": OpenAI(api_key=os.environ.get("OPENAI_API_KEY")),
        "model": "gpt-4o",
        "max_context": 15000,
        "tokenizer": AutoTokenizer.from_pretrained("Xenova/gpt-4o")
    },
    # "GPT_o1": {
    #     "client": OpenAI(api_key=os.environ.get("OPENAI_API_KEY")),
    #     "model": "o1-preview",
    #     "max_context": 15000,
    #     "tokenizer": AutoTokenizer.from_pretrained("Xenova/gpt-4o")
    # },
    "DEEPSEEK": {
        "client": OpenRouter(
            api_key=os.environ.get("OPENROUTER_API_KEY"),
        ),
        "model": "deepseek/deepseek-chat",
        "max_context": 30000,
        "tokenizer": AutoTokenizer.from_pretrained("Xenova/gpt-4o")
    },
    "DEEPSEEK_R1": {
        "client": OpenRouter(
            api_key=os.environ.get("OPENROUTER_API_KEY"),
        ),
        "model": "deepseek/deepseek-r1",
        "max_context": 30000,
        "tokenizer": AutoTokenizer.from_pretrained("Xenova/gpt-4o")
    },
}


def get_model_type():
    """
    Get the model type from Streamlit sidebar with model names
    """
    # Get the available model types from the MODEL_CONFIG keys
    available_models = list(MODEL_CONFIG.keys())
    
    # Create a list of display labels with just the model names
    model_display_labels = [
        MODEL_CONFIG[model_type]['model']
        for model_type in available_models
    ]
    
    # Add a sidebar selection for model name
    selected_model_name = st.sidebar.selectbox(
        "Select AI Model", 
        model_display_labels, 
        index=0
    )
    
    # Find the corresponding model type for the selected model name
    selected_model_type = next(
        model_type for model_type in available_models 
        if MODEL_CONFIG[model_type]['model'] == selected_model_name
    )
    
    return selected_model_type


# In the main application flow, replace the previous modelType assignment
modelType = get_model_type()

client = MODEL_CONFIG[modelType]["client"]
MODEL = MODEL_CONFIG[modelType]["model"]
TOOLS_MODEL = MODEL_CONFIG[modelType].get("tools_model") or MODEL
MAX_CONTEXT = MODEL_CONFIG[modelType]["max_context"]
tokenizer = MODEL_CONFIG[modelType]["tokenizer"]

isClaudeModel = modelType.startswith("CLAUDE")
isDeepSeekModel = modelType.startswith("DEEPSEEK")


def __countTokens(text):
    text = str(text)
    tokens = tokenizer.encode(text, add_special_tokens=False)
    return len(tokens)


# Initialize session state variables
if "ipAddress" not in st.session_state:
    st.session_state.ipAddress = st.context.headers.get("x-forwarded-for")
if "connection_string" not in st.session_state:
    st.session_state.connection_string = None
if "selected_table" not in st.session_state:
    st.session_state.selected_table = None
if "table_schema" not in st.session_state:
    st.session_state.table_schema = None
if "sample_data" not in st.session_state:
    st.session_state.sample_data = None
if "engine" not in st.session_state:
    st.session_state.engine = None


def connect_to_db(connection_string):
    try:
        engine = create_engine(connection_string)
        # Test the connection
        with engine.connect():
            pass
        st.session_state.engine = engine
        return True
    except Exception as e:
        st.error(f"Failed to connect to database: {str(e)}")
        return False


def get_table_schema(table_name):
    if not st.session_state.engine:
        return None
    
    inspector = inspect(st.session_state.engine)
    columns = inspector.get_columns(table_name)
    schema = {col['name']: str(col['type']) for col in columns}
    
    # Get table comment
    table_comment_query = """
        SELECT obj_description(c.oid) as table_comment
        FROM pg_class c
        JOIN pg_namespace n ON n.oid = c.relnamespace
        WHERE c.relname = :table_name
        AND n.nspname = 'public'
    """
    
    # Get column comments
    column_comments_query = """
        SELECT 
            cols.column_name,
            (
                SELECT pg_catalog.col_description(c.oid, cols.ordinal_position::int)
                FROM pg_catalog.pg_class c
                WHERE c.oid = (SELECT ('"' || cols.table_name || '"')::regclass::oid)
                    AND c.relname = cols.table_name
            ) as column_comment
        FROM information_schema.columns cols
        WHERE cols.table_name = :table_name
        AND cols.table_schema = 'public'
    """
    
    try:
        with st.session_state.engine.connect() as conn:
            # Get table comment
            table_comment_result = conn.execute(text(table_comment_query), {"table_name": table_name}).fetchone()
            table_comment = table_comment_result[0] if table_comment_result else None
            
            # Get column comments
            column_comments_result = conn.execute(text(column_comments_query), {"table_name": table_name}).fetchall()
            column_comments = {row[0]: row[1] for row in column_comments_result}
            
            # Create enhanced schema dictionary
            enhanced_schema = {
                "table_comment": table_comment,
                "columns": {
                    col_name: {
                        "type": schema[col_name],
                        "comment": column_comments.get(col_name)
                    }
                    for col_name in schema
                }
            }
            
            return enhanced_schema
    except Exception as e:
        st.error(f"Error fetching schema comments: {str(e)}")
        return schema  # Fallback to basic schema if comment retrieval fails


def get_sample_data(table_name):
    if not st.session_state.engine:
        return pd.DataFrame()  # Return empty DataFrame instead of None
    
    query = f"SELECT * FROM {table_name} ORDER BY 1 DESC LIMIT 3"
    try:
        with st.session_state.engine.connect() as conn:
            df = pd.read_sql(query, conn)
            return df
    except Exception as e:
        st.error(f"Error fetching sample data for {table_name}: {str(e)}")
        return pd.DataFrame()  # Return empty DataFrame on error


def clean_sql_response(response: str) -> str:
    """Extract clean SQL query from a potentially formatted response."""
    # If response contains SQL code block, extract it
    sql_block_match = re.search(r'```sql\n(.*?)\n```', response, re.DOTALL)
    if sql_block_match:
        return sql_block_match.group(1).strip()
    return response.strip()


def is_read_only_query(query: str) -> bool:
    """Check if the query is read-only (SELECT only)."""
    # Convert query to uppercase for case-insensitive comparison
    query_upper = query.upper()
    
    # List of SQL statements that modify data
    modification_statements = [
        'INSERT', 'UPDATE', 'DELETE', 'DROP', 'CREATE', 'ALTER', 'TRUNCATE', 
        'REPLACE', 'MERGE', 'UPSERT', 'GRANT', 'REVOKE'
    ]
    
    # Check if query starts with any modification statement
    return not any(query_upper.strip().startswith(stmt) for stmt in modification_statements)


def execute_query(query):
    if not st.session_state.engine:
        return None
    
    # Check if the query is read-only
    if not is_read_only_query(query):
        st.error("Error: Only SELECT queries are allowed for security reasons.")
        return None
    
    try:
        start_time = time.time()
        with st.spinner("Executing SQL query..."):
            # Create a connection and begin a transaction
            with st.session_state.engine.begin() as conn:
                # Execute the query using text() to ensure proper SQL compilation
                result = conn.execute(text(query))
                # Convert the result to a pandas DataFrame
                df = pd.DataFrame(result.fetchall(), columns=result.keys())
            execution_time = time.time() - start_time
            pprint(f"[Query Execution] Latency: {execution_time:.2f}s")
        return df
    except Exception as e:
        st.error(f"Error executing query: {str(e)}")
        return None


def generate_sql_query(user_query):
    # Build context for all selected tables
    tables_context = []
    for table_name, table_type in st.session_state.selected_tables.items():
        # Format schema in markdown
        schema_info = st.session_state.table_schemas[table_name]
        
        # Build markdown formatted schema
        schema_md = [f"\n\n### {table_type}: {table_name}"]
        
        # Add table comment if exists
        if schema_info.get("table_comment"):
            schema_md.append(f"> {schema_info['table_comment']}")
        
        # Add column details
        schema_md.append("\n**Columns:**")
        for col_name, col_info in schema_info["columns"].items():
            col_type = col_info["type"]
            col_comment = col_info.get("comment")
            
            # Format column with type and optional comment
            if col_comment:
                schema_md.append(f"- `{col_name}` ({col_type}) - {col_comment}")
            else:
                schema_md.append(f"- `{col_name}` ({col_type})")
        
        # Add sample data
        schema_md.append("\n**Sample Data:**")
        schema_md.append(st.session_state.sample_data[table_name].to_markdown(index=False))
        
        # Join all parts with newlines
        tables_context.append("\n".join(schema_md))

    prompt = f"""You are a SQL expert. Generate a valid PostgreSQL query based on the following context and user query.

<AVAILABLE_OBJECTS>
{chr(10).join(tables_context)}

Important:
1. Only generate SELECT queries - no INSERT, UPDATE, DELETE, or other data modification statements
2. Only return the SQL query, nothing else
3. The query should be valid PostgreSQL syntax
4. Do not include any explanations or comments
5. Make sure to handle NULL values appropriately
6. If joining tables, use appropriate join conditions based on the schema
7. Use table names with appropriate qualifiers to avoid ambiguity

User Query: {user_query}
"""

    prompt_tokens = __countTokens(prompt)
    print("\n")
    pprint(f"[{MODEL}] Prompt tokens for SQL generation: {prompt_tokens}")

    # Debug prompt in a Streamlit expander for better organization
    # Check if running locally based on Streamlit's origin header
    if 'localhost' in st.context.headers.get("Origin", ""):
        with st.expander("Debug: Prompt Generation"):
            st.write(f"\nUser Query: {user_query}")
            st.write("\nFull Prompt:")
            st.code(prompt, language="text")

    start_time = time.time()
    with st.spinner(f"Generating SQL query using {MODEL}..."):
        if isClaudeModel:
            response = client.messages.create(
                model=MODEL,
                max_tokens=1000,
                messages=[
                    {"role": "user", "content": prompt},
                ]
            )
            raw_response = response.content[0].text
        else:
            response = client.chat.completions.create(
                model=MODEL,
                messages=[
                    {"role": "user", "content": prompt},
                ]
            )
            raw_response = response.choices[0].message.content
        
        generation_time = time.time() - start_time
        pprint(f"[{MODEL}] Query Generation Latency: {generation_time:.2f}s")

    return clean_sql_response(raw_response)


# UI Components
st.title("SQL Query Assistant")

# Database Connection Section
st.header("1. Database Connection")
connection_string = st.text_input(
    "Enter PostgreSQL Connection String",
    value=st.session_state.connection_string if st.session_state.connection_string else "",
    type="password"
)

if connection_string and connection_string != st.session_state.connection_string:
    if connect_to_db(connection_string):
        st.session_state.connection_string = connection_string
        st.success("Successfully connected to database!")

# Table Selection Section
if st.session_state.connection_string:
    st.header("2. Database Object Selection")
    inspector = inspect(st.session_state.engine)
    
    # Get both tables and views
    tables = inspector.get_table_names()
    views = inspector.get_view_names()
    
    # Create a list of tuples with (name, type) for all database objects
    db_objects = [(table, 'Table') for table in tables] + [(view, 'View') for view in views]
    db_objects.sort(key=lambda x: x[0])  # Sort alphabetically by name
    
    # Extract just the names for the multiselect
    object_names = [obj[0] for obj in db_objects]
    
    # Default to 'lsq_leads' if present
    default_selections = ['lsq_leads'] if 'lsq_leads' in object_names else []
    
    # Create multiselect for table/view selection
    selected_objects = st.multiselect(
        "Select tables/views",
        options=object_names,
        default=default_selections,
        help="You can select multiple tables/views to query across them"
    )
    
    # Display selected object types
    if selected_objects:
        st.write("Selected objects:")
        for obj in selected_objects:
            obj_type = next(obj_type for obj_name, obj_type in db_objects if obj_name == obj)
            st.write(f"- {obj}: {obj_type}")
    
    # Create containers for schema and data
    schema_container = st.container()
    data_container = st.container()
    
    # Initialize or reset session state for selected objects
    if selected_objects:
        # Always ensure dictionaries exist in session state
        if not isinstance(st.session_state.get("selected_tables"), dict):
            st.session_state.selected_tables = {}
        if not isinstance(st.session_state.get("table_schemas"), dict):
            st.session_state.table_schemas = {}
        if not isinstance(st.session_state.get("sample_data"), dict):
            st.session_state.sample_data = {}
        
        # Clear previous data for tables that are no longer selected
        current_tables = set(selected_objects)
        previous_tables = set(st.session_state.selected_tables.keys())
        removed_tables = previous_tables - current_tables
        
        for table in removed_tables:
            if table in st.session_state.selected_tables:
                del st.session_state.selected_tables[table]
            if table in st.session_state.table_schemas:
                del st.session_state.table_schemas[table]
            if table in st.session_state.sample_data:
                del st.session_state.sample_data[table]
        
        # Update session state with new selections
        for obj in selected_objects:
            # Update selected tables
            st.session_state.selected_tables[obj] = next(
                obj_type for obj_name, obj_type in db_objects if obj_name == obj
            )
            
            # Fetch and store schema
            schema = get_table_schema(obj)
            if schema:
                st.session_state.table_schemas[obj] = schema
            
            # Fetch and store sample data
            sample_data = get_sample_data(obj)
            if not sample_data.empty:
                st.session_state.sample_data[obj] = sample_data
        
        # Display schema and sample data for each selected object
        with schema_container:
            st.subheader("Table/View Schemas")
            for obj in selected_objects:
                if obj in st.session_state.table_schemas:
                    st.write(f"**{obj} Schema:**")
                    st.json(st.session_state.table_schemas[obj])
                    st.write("---")
                else:
                    st.warning(f"Could not fetch schema for {obj}")
        
        with data_container:
            st.subheader("Sample Data")
            for obj in selected_objects:
                if obj in st.session_state.sample_data and not st.session_state.sample_data[obj].empty:
                    st.write(f"**{obj} (Last 3 rows):**")
                    st.dataframe(
                        st.session_state.sample_data[obj],
                        use_container_width=True,
                        hide_index=True
                    )
                    st.write("---")
                else:
                    st.warning(f"No sample data available for {obj}")

# Query Input Section
if st.session_state.get("selected_tables"):
    st.header("3. Query Input")
    user_query = st.text_area("Enter your query in plain English")
    
    if st.button("Generate and Execute Query"):
        if user_query:
            # Generate SQL query
            sql_query = generate_sql_query(user_query)
            
            # Display the generated query
            st.subheader("Generated SQL Query")
            st.code(sql_query, language="sql")
            
            # Execute the query
            results = execute_query(sql_query)
            if results is not None:
                st.subheader("Query Results")
                st.dataframe(results)