Ari commited on
Commit
cb5f50e
·
verified ·
1 Parent(s): ed53cb3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -47
app.py CHANGED
@@ -3,19 +3,31 @@ import streamlit as st
3
  import pandas as pd
4
  import sqlite3
5
  import openai
6
- from langchain_openai import OpenAI, OpenAIEmbeddings # Use updated imports
7
- from langchain_community.agent_toolkits.sql.base import create_sql_agent
8
- from langchain_community.utilities import SQLDatabase
9
- from langchain_community.document_loaders import CSVLoader
10
  from langchain_community.vectorstores import FAISS
11
  from langchain.chains import RetrievalQA
 
 
 
12
  import sqlparse
13
  import logging
14
 
15
- # OpenAI API key (ensure it is securely stored)
16
  openai.api_key = os.getenv("OPENAI_API_KEY")
17
-
18
- # Step 1: Upload CSV data file (or use default)
 
 
 
 
 
 
 
 
 
 
19
  csv_file = st.file_uploader("Upload your CSV file", type=["csv"])
20
  if csv_file is None:
21
  data = pd.read_csv("default_data.csv") # Use default CSV if no file is uploaded
@@ -25,7 +37,7 @@ else:
25
  st.write(f"Data Preview ({csv_file.name}):")
26
  st.dataframe(data.head())
27
 
28
- # Step 2: Load CSV data into a persistent SQLite database
29
  db_file = 'my_database.db'
30
  conn = sqlite3.connect(db_file)
31
  table_name = csv_file.name.split('.')[0] if csv_file else "default_table"
@@ -33,76 +45,65 @@ data.to_sql(table_name, conn, index=False, if_exists='replace')
33
 
34
  # SQL table metadata (for validation and schema)
35
  valid_columns = list(data.columns)
36
-
37
- # Debug: Display valid columns for user to verify
38
  st.write(f"Valid columns: {valid_columns}")
39
 
40
- # Step 3: Set up the SQL Database for LangChain
 
 
 
 
 
 
 
 
41
  db = SQLDatabase.from_uri(f'sqlite:///{db_file}')
42
- db.raw_connection = conn # Use the persistent database connection for LangChain
43
 
44
- # Step 4: Create the SQL agent with increased iteration and time limits
45
  sql_agent = create_sql_agent(
46
- OpenAI(temperature=0),
47
  db=db,
48
  verbose=True,
49
  max_iterations=20, # Increased iteration limit
50
  max_execution_time=90 # Set timeout limit to 90 seconds
51
  )
52
 
53
- # Step 5: Use FAISS with RAG for context retrieval
54
- embeddings = OpenAIEmbeddings()
 
 
 
 
 
 
55
  loader = CSVLoader(file_path=csv_file.name if csv_file else "default_data.csv")
56
  documents = loader.load()
57
-
58
  vector_store = FAISS.from_documents(documents, embeddings)
59
  retriever = vector_store.as_retriever()
60
- rag_chain = RetrievalQA.from_chain_type(llm=OpenAI(temperature=0), retriever=retriever)
61
-
62
- # Step 6: Define SQL validation helpers
63
- def validate_sql(query, valid_columns):
64
- """Validates the SQL query by ensuring it references only valid columns."""
65
- parsed = sqlparse.parse(query)
66
- for token in parsed[0].tokens:
67
- if token.ttype is None: # If it's a column name
68
- column_name = str(token).strip()
69
- if column_name not in valid_columns:
70
- return False
71
- return True
72
 
73
- def validate_sql_with_sqlparse(query):
74
- """Validates SQL syntax using sqlparse."""
75
- parsed_query = sqlparse.parse(query)
76
- return len(parsed_query) > 0
77
-
78
- # Step 7: Generate SQL query based on user input and run it with LangChain SQL Agent
79
  user_prompt = st.text_input("Enter your natural language prompt:")
80
  if user_prompt:
81
  try:
82
- # Step 8: Add valid column names to the prompt
83
  column_hints = f" Use only these columns: {', '.join(valid_columns)}"
84
  prompt_with_columns = user_prompt + column_hints
85
 
86
- # Step 9: Retrieve context using RAG
87
- context = rag_chain.invoke(prompt_with_columns) # Updated from .run to .invoke
88
  st.write(f"Retrieved Context: {context}")
89
 
90
- # Debugging step: Inspect context retrieval
91
- st.write(f"Retrieved Context Debug: {context}")
92
-
93
- # Step 10: Generate SQL query using SQL agent
94
- generated_sql = sql_agent.run(f"{user_prompt} {context}")
95
-
96
- # Debug: Display generated SQL query for inspection
97
  st.write(f"Generated SQL Query: {generated_sql}")
98
 
99
- # Step 11: Validate SQL query
100
  if not validate_sql_with_sqlparse(generated_sql):
101
  st.write("Generated SQL is not valid.")
102
  elif not validate_sql(generated_sql, valid_columns):
103
  st.write("Generated SQL references invalid columns.")
104
  else:
105
- # Step 12: Execute SQL query
106
  result = pd.read_sql(generated_sql, conn)
107
  st.write("Query Results:")
108
  st.dataframe(result)
 
3
  import pandas as pd
4
  import sqlite3
5
  import openai
6
+ from langchain_openai import AzureChatOpenAI, AzureOpenAIEmbedding
7
+ from langchain.agents import create_sql_agent
8
+ from langchain.sql_database import SQLDatabase
 
9
  from langchain_community.vectorstores import FAISS
10
  from langchain.chains import RetrievalQA
11
+ from langchain_community.document_loaders import CSVLoader
12
+ from langchain.prompts import ChatPromptTemplate, FewShotPromptTemplate
13
+ from langchain_core.prompts import SystemMessagePromptTemplate, HumanMessagePromptTemplate
14
  import sqlparse
15
  import logging
16
 
17
+ # Load environment variables for Azure OpenAI
18
  openai.api_key = os.getenv("OPENAI_API_KEY")
19
+ api_key = os.getenv("OPENAI_API_KEY")
20
+ endpoint = os.getenv("azure_endpoint")
21
+ api_type = os.getenv("OPENAI_API_TYPE")
22
+ api_version = os.getenv("OPENAI_API_VERSION")
23
+
24
+ # Models
25
+ chat_model = os.getenv("chat_model")
26
+ embed_model = os.getenv("embed_model")
27
+ chat_deployment = os.getenv("chat_deployment")
28
+ embed_deployment = os.getenv("embed_deployment")
29
+
30
+ # Load CSV file for data
31
  csv_file = st.file_uploader("Upload your CSV file", type=["csv"])
32
  if csv_file is None:
33
  data = pd.read_csv("default_data.csv") # Use default CSV if no file is uploaded
 
37
  st.write(f"Data Preview ({csv_file.name}):")
38
  st.dataframe(data.head())
39
 
40
+ # Use a persistent SQLite database instead of in-memory
41
  db_file = 'my_database.db'
42
  conn = sqlite3.connect(db_file)
43
  table_name = csv_file.name.split('.')[0] if csv_file else "default_table"
 
45
 
46
  # SQL table metadata (for validation and schema)
47
  valid_columns = list(data.columns)
 
 
48
  st.write(f"Valid columns: {valid_columns}")
49
 
50
+ # Set up the SQL Database for LangChain with AzureOpenAI configuration
51
+ llm = AzureChatOpenAI(
52
+ temperature=0,
53
+ model=chat_model,
54
+ deployment_name=chat_deployment,
55
+ api_key=api_key,
56
+ azure_endpoint=endpoint,
57
+ api_version=api_version
58
+ )
59
  db = SQLDatabase.from_uri(f'sqlite:///{db_file}')
60
+ db.raw_connection = conn
61
 
62
+ # Create the SQL agent with prompt and toolkit for SQL querying
63
  sql_agent = create_sql_agent(
64
+ llm=llm,
65
  db=db,
66
  verbose=True,
67
  max_iterations=20, # Increased iteration limit
68
  max_execution_time=90 # Set timeout limit to 90 seconds
69
  )
70
 
71
+ # Set up FAISS for retrieval
72
+ embeddings = AzureOpenAIEmbedding(
73
+ model=embed_model,
74
+ deployment_name=embed_deployment,
75
+ api_key=api_key,
76
+ azure_endpoint=endpoint,
77
+ api_version=api_version
78
+ )
79
  loader = CSVLoader(file_path=csv_file.name if csv_file else "default_data.csv")
80
  documents = loader.load()
 
81
  vector_store = FAISS.from_documents(documents, embeddings)
82
  retriever = vector_store.as_retriever()
83
+ rag_chain = RetrievalQA.from_chain_type(llm=llm, retriever=retriever)
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ # Insight extraction and SQL query generation
 
 
 
 
 
86
  user_prompt = st.text_input("Enter your natural language prompt:")
87
  if user_prompt:
88
  try:
89
+ # Add column hints to the user prompt
90
  column_hints = f" Use only these columns: {', '.join(valid_columns)}"
91
  prompt_with_columns = user_prompt + column_hints
92
 
93
+ # Retrieve context using FAISS and RAG
94
+ context = rag_chain.run(prompt_with_columns)
95
  st.write(f"Retrieved Context: {context}")
96
 
97
+ # Generate SQL query using SQL agent
98
+ generated_sql = sql_agent.run(f"{prompt_with_columns} {context}")
 
 
 
 
 
99
  st.write(f"Generated SQL Query: {generated_sql}")
100
 
101
+ # Validate SQL query and execute
102
  if not validate_sql_with_sqlparse(generated_sql):
103
  st.write("Generated SQL is not valid.")
104
  elif not validate_sql(generated_sql, valid_columns):
105
  st.write("Generated SQL references invalid columns.")
106
  else:
 
107
  result = pd.read_sql(generated_sql, conn)
108
  st.write("Query Results:")
109
  st.dataframe(result)