Spaces:
Sleeping
Sleeping
DrishtiSharma
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -18,12 +18,11 @@ from langchain_community.tools.sql_database.tool import (
|
|
18 |
QuerySQLDataBaseTool,
|
19 |
)
|
20 |
from langchain_community.utilities.sql_database import SQLDatabase
|
|
|
21 |
import tempfile
|
22 |
|
23 |
-
# Setup GROQ API Key
|
24 |
os.environ["GROQ_API_KEY"] = st.secrets.get("GROQ_API_KEY", "")
|
25 |
|
26 |
-
# Callback handler for logging LLM responses
|
27 |
class Event:
|
28 |
def __init__(self, event, text):
|
29 |
self.event = event
|
@@ -43,112 +42,109 @@ class LLMCallbackHandler(BaseCallbackHandler):
|
|
43 |
with self.log_path.open("a", encoding="utf-8") as file:
|
44 |
file.write(json.dumps({"event": "llm_end", "text": generation, "timestamp": datetime.now().isoformat()}) + "\n")
|
45 |
|
46 |
-
# LLM Setup
|
47 |
llm = ChatGroq(
|
48 |
temperature=0,
|
49 |
model_name="mixtral-8x7b-32768",
|
50 |
callbacks=[LLMCallbackHandler(Path("prompts.jsonl"))],
|
51 |
)
|
52 |
|
53 |
-
|
54 |
-
st.
|
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 |
-
# Clean up
|
154 |
-
temp_dir.cleanup()
|
|
|
18 |
QuerySQLDataBaseTool,
|
19 |
)
|
20 |
from langchain_community.utilities.sql_database import SQLDatabase
|
21 |
+
from datasets import load_dataset
|
22 |
import tempfile
|
23 |
|
|
|
24 |
os.environ["GROQ_API_KEY"] = st.secrets.get("GROQ_API_KEY", "")
|
25 |
|
|
|
26 |
class Event:
|
27 |
def __init__(self, event, text):
|
28 |
self.event = event
|
|
|
42 |
with self.log_path.open("a", encoding="utf-8") as file:
|
43 |
file.write(json.dumps({"event": "llm_end", "text": generation, "timestamp": datetime.now().isoformat()}) + "\n")
|
44 |
|
|
|
45 |
llm = ChatGroq(
|
46 |
temperature=0,
|
47 |
model_name="mixtral-8x7b-32768",
|
48 |
callbacks=[LLMCallbackHandler(Path("prompts.jsonl"))],
|
49 |
)
|
50 |
|
51 |
+
st.title("SQL-RAG using CrewAI π")
|
52 |
+
st.write("Analyze and summarize Hugging Face datasets using natural language queries with SQL-based retrieval.")
|
53 |
+
|
54 |
+
default_dataset = "datascience/ds-salaries"
|
55 |
+
st.text("Example dataset: `datascience/ds-salaries` (You can enter your own dataset name)")
|
56 |
+
|
57 |
+
dataset_name = st.text_input("Enter Hugging Face dataset name:", value=default_dataset)
|
58 |
+
|
59 |
+
if dataset_name:
|
60 |
+
with st.spinner("Loading dataset..."):
|
61 |
+
try:
|
62 |
+
dataset = load_dataset(dataset_name, split="train")
|
63 |
+
df = pd.DataFrame(dataset)
|
64 |
+
st.success(f"Dataset '{dataset_name}' loaded successfully!")
|
65 |
+
st.write("Preview of the dataset:")
|
66 |
+
st.dataframe(df.head())
|
67 |
+
|
68 |
+
temp_dir = tempfile.TemporaryDirectory()
|
69 |
+
db_path = os.path.join(temp_dir.name, "data.db")
|
70 |
+
connection = sqlite3.connect(db_path)
|
71 |
+
df.to_sql("data_table", connection, if_exists="replace", index=False)
|
72 |
+
db = SQLDatabase.from_uri(f"sqlite:///{db_path}")
|
73 |
+
|
74 |
+
@tool("list_tables")
|
75 |
+
def list_tables() -> str:
|
76 |
+
return ListSQLDatabaseTool(db=db).invoke("")
|
77 |
+
|
78 |
+
@tool("tables_schema")
|
79 |
+
def tables_schema(tables: str) -> str:
|
80 |
+
return InfoSQLDatabaseTool(db=db).invoke(tables)
|
81 |
+
|
82 |
+
@tool("execute_sql")
|
83 |
+
def execute_sql(sql_query: str) -> str:
|
84 |
+
return QuerySQLDataBaseTool(db=db).invoke(sql_query)
|
85 |
+
|
86 |
+
@tool("check_sql")
|
87 |
+
def check_sql(sql_query: str) -> str:
|
88 |
+
return QuerySQLCheckerTool(db=db, llm=llm).invoke({"query": sql_query})
|
89 |
+
|
90 |
+
sql_dev = Agent(
|
91 |
+
role="Database Developer",
|
92 |
+
goal="Extract data from the database.",
|
93 |
+
llm=llm,
|
94 |
+
tools=[list_tables, tables_schema, execute_sql, check_sql],
|
95 |
+
allow_delegation=False,
|
96 |
+
)
|
97 |
+
|
98 |
+
data_analyst = Agent(
|
99 |
+
role="Data Analyst",
|
100 |
+
goal="Analyze and provide insights.",
|
101 |
+
llm=llm,
|
102 |
+
allow_delegation=False,
|
103 |
+
)
|
104 |
+
|
105 |
+
report_writer = Agent(
|
106 |
+
role="Report Editor",
|
107 |
+
goal="Summarize the analysis.",
|
108 |
+
llm=llm,
|
109 |
+
allow_delegation=False,
|
110 |
+
)
|
111 |
+
|
112 |
+
extract_data = Task(
|
113 |
+
description="Extract data required for the query: {query}.",
|
114 |
+
expected_output="Database result for the query",
|
115 |
+
agent=sql_dev,
|
116 |
+
)
|
117 |
+
|
118 |
+
analyze_data = Task(
|
119 |
+
description="Analyze the data for: {query}.",
|
120 |
+
expected_output="Detailed analysis text",
|
121 |
+
agent=data_analyst,
|
122 |
+
context=[extract_data],
|
123 |
+
)
|
124 |
+
|
125 |
+
write_report = Task(
|
126 |
+
description="Summarize the analysis into a short report.",
|
127 |
+
expected_output="Markdown report",
|
128 |
+
agent=report_writer,
|
129 |
+
context=[analyze_data],
|
130 |
+
)
|
131 |
+
|
132 |
+
crew = Crew(
|
133 |
+
agents=[sql_dev, data_analyst, report_writer],
|
134 |
+
tasks=[extract_data, analyze_data, write_report],
|
135 |
+
process=Process.sequential,
|
136 |
+
verbose=2,
|
137 |
+
memory=False,
|
138 |
+
)
|
139 |
+
|
140 |
+
query = st.text_input("Enter your query:", placeholder="e.g., 'How does salary vary by company size?'")
|
141 |
+
if query:
|
142 |
+
with st.spinner("Processing your query..."):
|
143 |
+
inputs = {"query": query}
|
144 |
+
result = crew.kickoff(inputs=inputs)
|
145 |
+
st.markdown("### Analysis Report:")
|
146 |
+
st.markdown(result)
|
147 |
+
|
148 |
+
temp_dir.cleanup()
|
149 |
+
except Exception as e:
|
150 |
+
st.error(f"Error loading dataset: {e}")
|
|
|
|