Commit
·
ec83ec8
1
Parent(s):
38330c2
Pushing code to HuggingFace space
Browse files
app.py
CHANGED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import subprocess
|
4 |
+
import logging
|
5 |
+
import asyncio
|
6 |
+
from src.agents.nl_sql_agent import NLSQLAgent
|
7 |
+
|
8 |
+
logging.basicConfig(level=logging.INFO)
|
9 |
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
10 |
+
logging.getLogger("chromadb").setLevel(logging.WARNING)
|
11 |
+
|
12 |
+
print("--- Starting Hugging Face Space setup ---")
|
13 |
+
|
14 |
+
SETUP_DATABASE_SCRIPT = os.path.join('src', 'setup_database.py')
|
15 |
+
RAG_INDEX_SCRIPT = os.path.join('src', 'rag_index.py')
|
16 |
+
|
17 |
+
if not os.environ.get("NEBIUS_API_KEY"):
|
18 |
+
print("FATAL ERROR: NEBIUS_API_KEY environment variable not set. This is required for Nebius LLMs and Embeddings.")
|
19 |
+
|
20 |
+
try:
|
21 |
+
print(f"Running database setup script: {SETUP_DATABASE_SCRIPT}...")
|
22 |
+
subprocess.run(["python", SETUP_DATABASE_SCRIPT], check=True, capture_output=True)
|
23 |
+
print("Database setup complete.")
|
24 |
+
|
25 |
+
print(f"Running RAG indexing script: {RAG_INDEX_SCRIPT}...")
|
26 |
+
subprocess.run(["python", RAG_INDEX_SCRIPT], check=True, capture_output=True)
|
27 |
+
print("RAG indexing complete.")
|
28 |
+
|
29 |
+
except subprocess.CalledProcessError as e:
|
30 |
+
print(f"Error during initial setup. Script failed with exit code {e.returncode}.")
|
31 |
+
print(f"Stdout:\n{e.stdout.decode()}")
|
32 |
+
print(f"Stderr:\n{e.stderr.decode()}")
|
33 |
+
print("Exiting application due to critical setup failure.")
|
34 |
+
exit(1)
|
35 |
+
|
36 |
+
print("--- Hugging Face Space setup complete. Initializing Agent ---")
|
37 |
+
|
38 |
+
# --- Initialize the NL-to-SQL Agent ---
|
39 |
+
nl_sql_agent_instance = NLSQLAgent()
|
40 |
+
print("NLSQLAgent initialized.")
|
41 |
+
|
42 |
+
# --- Define Gradio Interface Functions ---
|
43 |
+
async def query_agent_gradio(user_query: str) -> str:
|
44 |
+
if not user_query.strip():
|
45 |
+
return "Please enter a question to get started!"
|
46 |
+
|
47 |
+
try:
|
48 |
+
response = await nl_sql_agent_instance.process_query(user_query)
|
49 |
+
return response
|
50 |
+
except Exception as e:
|
51 |
+
logging.error(f"Error processing query in Gradio app: {e}", exc_info=True)
|
52 |
+
return f"An internal error occurred: {type(e).__name__}: {str(e)}. Please check the Space logs for more details."
|
53 |
+
|
54 |
+
# --- Create Gradio Interface ---
|
55 |
+
iface = gr.Interface(
|
56 |
+
fn=query_agent_gradio,
|
57 |
+
inputs=gr.Textbox(lines=2, placeholder="Ask a question about your sales data (e.g., 'What is the total number of sales?', 'Show me top 5 products by quantity sold')..."),
|
58 |
+
outputs=gr.Markdown(),
|
59 |
+
title="📊 AI-Powered Data Analyst Assistant (NL-to-SQL Demo)",
|
60 |
+
description=(
|
61 |
+
"Ask natural language questions to get insights from your sales database. "
|
62 |
+
"This demo exclusively uses the NL-to-SQL Agent, leveraging fine-tuned LLMs, RAG for schema context, and SQLite. "
|
63 |
+
"Example questions: 'What are the names of customers in the North region?', 'How much revenue did we generate from Electronics products?', 'Show me the total revenue for each month over the last six months, ordered by month.'"
|
64 |
+
),
|
65 |
+
examples=[
|
66 |
+
["What is the total number of sales?"],
|
67 |
+
["What are the names of customers in the North region?"],
|
68 |
+
["How much revenue did we generate from Electronics products?"],
|
69 |
+
["Which customer has the most sales in the past one month?"],
|
70 |
+
["Show me the total revenue for each month over the last six months, ordered by month."],
|
71 |
+
["Which are our top 5 products by total quantity sold across all time?"],
|
72 |
+
["What is the average amount per sale for each product category?"],
|
73 |
+
["How many unique customers have made a purchase in each region over the last year?"],
|
74 |
+
["What is the total revenue generated by customers from each region?"]
|
75 |
+
],
|
76 |
+
allow_flagging="auto",
|
77 |
+
analytics_enabled=True
|
78 |
+
)
|
79 |
+
|
80 |
+
if __name__ == "__main__":
|
81 |
+
print("Launching Gradio app...")
|
82 |
+
iface.launch(share=False)
|
requirements.txt
CHANGED
Binary files a/requirements.txt and b/requirements.txt differ
|
|
src/agents/agent_models/__pycache__/models.cpython-313.pyc
CHANGED
Binary files a/src/agents/agent_models/__pycache__/models.cpython-313.pyc and b/src/agents/agent_models/__pycache__/models.cpython-313.pyc differ
|
|
src/agents/agent_tools/__pycache__/schema_retriever_tool.cpython-313.pyc
CHANGED
Binary files a/src/agents/agent_tools/__pycache__/schema_retriever_tool.cpython-313.pyc and b/src/agents/agent_tools/__pycache__/schema_retriever_tool.cpython-313.pyc differ
|
|
src/agents/agent_tools/schema_retriever_tool.py
CHANGED
@@ -1,5 +1,3 @@
|
|
1 |
-
# src/agents/tools/schema_retriever_tool.py
|
2 |
-
|
3 |
import os
|
4 |
import logging
|
5 |
import chromadb
|
|
|
|
|
|
|
1 |
import os
|
2 |
import logging
|
3 |
import chromadb
|
src/agents/nl_sql_agent.py
CHANGED
@@ -12,7 +12,7 @@ logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
|
|
12 |
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
|
13 |
|
14 |
class NLSQLAgent:
|
15 |
-
def __init__(self
|
16 |
"""
|
17 |
Initializes the NL-to-SQL Agent, which translates natural language to SQL, executes it, and provides answers.
|
18 |
|
@@ -98,11 +98,7 @@ if __name__ == "__main__":
|
|
98 |
elif YOUR_FINETUNED_MODEL_ID == "your-finetuned-model-id":
|
99 |
print("Error: Please replace 'your-finetuned-model-id' with your actual model ID.")
|
100 |
else:
|
101 |
-
nl_sql_agent = NLSQLAgent(
|
102 |
-
model_name=YOUR_FINETUNED_MODEL_ID,
|
103 |
-
api_key=NEBIUS_API_KEY,
|
104 |
-
base_url=NEBIUS_BASE_URL
|
105 |
-
)
|
106 |
|
107 |
print("\nNL-to-SQL Agent initialized. Ask a question about your sales database.")
|
108 |
|
|
|
12 |
logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
|
13 |
|
14 |
class NLSQLAgent:
|
15 |
+
def __init__(self):
|
16 |
"""
|
17 |
Initializes the NL-to-SQL Agent, which translates natural language to SQL, executes it, and provides answers.
|
18 |
|
|
|
98 |
elif YOUR_FINETUNED_MODEL_ID == "your-finetuned-model-id":
|
99 |
print("Error: Please replace 'your-finetuned-model-id' with your actual model ID.")
|
100 |
else:
|
101 |
+
nl_sql_agent = NLSQLAgent()
|
|
|
|
|
|
|
|
|
102 |
|
103 |
print("\nNL-to-SQL Agent initialized. Ask a question about your sales database.")
|
104 |
|