Spaces:
Sleeping
Sleeping
DrishtiSharma
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,17 +1,16 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
import sqlite3
|
4 |
-
|
5 |
-
|
6 |
from pathlib import Path
|
7 |
-
from
|
8 |
-
from typing import Any, Dict, List, Tuple, Union
|
9 |
-
|
10 |
-
import pandas as pd
|
11 |
from crewai import Agent, Crew, Process, Task
|
12 |
from crewai_tools import tool
|
13 |
-
from
|
|
|
14 |
from langchain.schema.output import LLMResult
|
|
|
15 |
from langchain_community.tools.sql_database.tool import (
|
16 |
InfoSQLDatabaseTool,
|
17 |
ListSQLDatabaseTool,
|
@@ -19,6 +18,137 @@ from langchain_community.tools.sql_database.tool import (
|
|
19 |
QuerySQLDataBaseTool,
|
20 |
)
|
21 |
from langchain_community.utilities.sql_database import SQLDatabase
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
import sqlite3
|
4 |
+
import os
|
5 |
+
import json
|
6 |
from pathlib import Path
|
7 |
+
from datetime import datetime, timezone
|
|
|
|
|
|
|
8 |
from crewai import Agent, Crew, Process, Task
|
9 |
from crewai_tools import tool
|
10 |
+
from langchain_core.prompts import ChatPromptTemplate
|
11 |
+
from langchain_groq import ChatGroq
|
12 |
from langchain.schema.output import LLMResult
|
13 |
+
from langchain_core.callbacks.base import BaseCallbackHandler
|
14 |
from langchain_community.tools.sql_database.tool import (
|
15 |
InfoSQLDatabaseTool,
|
16 |
ListSQLDatabaseTool,
|
|
|
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
|
30 |
+
self.timestamp = datetime.now(timezone.utc).isoformat()
|
31 |
+
self.text = text
|
32 |
+
|
33 |
+
class LLMCallbackHandler(BaseCallbackHandler):
|
34 |
+
def __init__(self, log_path: Path):
|
35 |
+
self.log_path = log_path
|
36 |
+
|
37 |
+
def on_llm_start(self, serialized, prompts, **kwargs):
|
38 |
+
with self.log_path.open("a", encoding="utf-8") as file:
|
39 |
+
file.write(json.dumps({"event": "llm_start", "text": prompts[0], "timestamp": datetime.now().isoformat()}) + "\n")
|
40 |
+
|
41 |
+
def on_llm_end(self, response: LLMResult, **kwargs):
|
42 |
+
generation = response.generations[-1][-1].message.content
|
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 |
+
# App Header
|
54 |
+
st.title("Dynamic Query Analysis with CrewAI π")
|
55 |
+
st.write("Provide your query, and the app will extract, analyze, and summarize the data dynamically.")
|
56 |
+
|
57 |
+
# File Upload for Dataset
|
58 |
+
uploaded_file = st.file_uploader("Upload your dataset (CSV file)", type=["csv"])
|
59 |
+
|
60 |
+
if uploaded_file:
|
61 |
+
st.success("File uploaded successfully!")
|
62 |
+
|
63 |
+
# Temporary directory for SQLite DB
|
64 |
+
temp_dir = tempfile.TemporaryDirectory()
|
65 |
+
db_path = os.path.join(temp_dir.name, "data.db")
|
66 |
+
|
67 |
+
# Create SQLite database
|
68 |
+
df = pd.read_csv(uploaded_file)
|
69 |
+
connection = sqlite3.connect(db_path)
|
70 |
+
df.to_sql("data_table", connection, if_exists="replace", index=False)
|
71 |
+
|
72 |
+
db = SQLDatabase.from_uri(f"sqlite:///{db_path}")
|
73 |
+
|
74 |
+
# Tools
|
75 |
+
@tool("list_tables")
|
76 |
+
def list_tables() -> str:
|
77 |
+
return ListSQLDatabaseTool(db=db).invoke("")
|
78 |
+
|
79 |
+
@tool("tables_schema")
|
80 |
+
def tables_schema(tables: str) -> str:
|
81 |
+
return InfoSQLDatabaseTool(db=db).invoke(tables)
|
82 |
+
|
83 |
+
@tool("execute_sql")
|
84 |
+
def execute_sql(sql_query: str) -> str:
|
85 |
+
return QuerySQLDataBaseTool(db=db).invoke(sql_query)
|
86 |
+
|
87 |
+
@tool("check_sql")
|
88 |
+
def check_sql(sql_query: str) -> str:
|
89 |
+
return QuerySQLCheckerTool(db=db, llm=llm).invoke({"query": sql_query})
|
90 |
+
|
91 |
+
# Agents
|
92 |
+
sql_dev = Agent(
|
93 |
+
role="Senior Database Developer",
|
94 |
+
goal="Extract data from the database based on user query",
|
95 |
+
llm=llm,
|
96 |
+
tools=[list_tables, tables_schema, execute_sql, check_sql],
|
97 |
+
allow_delegation=False,
|
98 |
+
)
|
99 |
+
|
100 |
+
data_analyst = Agent(
|
101 |
+
role="Senior Data Analyst",
|
102 |
+
goal="Analyze the database response and provide insights",
|
103 |
+
llm=llm,
|
104 |
+
allow_delegation=False,
|
105 |
+
)
|
106 |
+
|
107 |
+
report_writer = Agent(
|
108 |
+
role="Senior Report Editor",
|
109 |
+
goal="Summarize the analysis into a short report",
|
110 |
+
llm=llm,
|
111 |
+
allow_delegation=False,
|
112 |
+
)
|
113 |
+
|
114 |
+
# Tasks
|
115 |
+
extract_data = Task(
|
116 |
+
description="Extract data required for the query: {query}.",
|
117 |
+
expected_output="Database result for the query",
|
118 |
+
agent=sql_dev,
|
119 |
+
)
|
120 |
+
|
121 |
+
analyze_data = Task(
|
122 |
+
description="Analyze the data and generate insights for: {query}.",
|
123 |
+
expected_output="Detailed analysis text",
|
124 |
+
agent=data_analyst,
|
125 |
+
context=[extract_data],
|
126 |
+
)
|
127 |
+
|
128 |
+
write_report = Task(
|
129 |
+
description="Summarize the analysis into a concise executive report.",
|
130 |
+
expected_output="Markdown report",
|
131 |
+
agent=report_writer,
|
132 |
+
context=[analyze_data],
|
133 |
+
)
|
134 |
+
|
135 |
+
# Crew
|
136 |
+
crew = Crew(
|
137 |
+
agents=[sql_dev, data_analyst, report_writer],
|
138 |
+
tasks=[extract_data, analyze_data, write_report],
|
139 |
+
process=Process.sequential,
|
140 |
+
verbose=2,
|
141 |
+
memory=False,
|
142 |
+
)
|
143 |
+
|
144 |
+
# User Input Query
|
145 |
+
query = st.text_input("Enter your query:")
|
146 |
+
if query:
|
147 |
+
with st.spinner("Processing your query..."):
|
148 |
+
inputs = {"query": query}
|
149 |
+
result = crew.kickoff(inputs=inputs)
|
150 |
+
st.markdown("### Analysis Report:")
|
151 |
+
st.markdown(result)
|
152 |
+
|
153 |
+
# Clean up
|
154 |
+
temp_dir.cleanup()
|