Skip to content

Commit a6de1d7

Browse files
committed
refactor: Update import paths and clean up code structure; add basic usage demo for Querypls functionality
1 parent e511797 commit a6de1d7

File tree

18 files changed

+422
-244
lines changed

18 files changed

+422
-244
lines changed

.devcontainer/devcontainer.json

Lines changed: 0 additions & 33 deletions
This file was deleted.

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ __pycache__/
1414
# Installer logs
1515
pip-log.txt
1616
pip-delete-this-directory.txt
17+
test_*
18+
run_*
1719

1820
# Unit test / coverage reports
1921
.coverage

examples/basic_usage_demo.py

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Basic usage demo for Querypls backend functionality.
4+
Demonstrates conversation, SQL generation, and CSV analysis.
5+
"""
6+
7+
import sys
8+
import os
9+
10+
# Add the project root to Python path
11+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
12+
13+
from src.services.routing_service import IntelligentRoutingService
14+
from src.backend.orchestrator import BackendOrchestrator
15+
from src.schemas.requests import NewChatRequest
16+
17+
18+
def demo_conversation():
19+
"""Demo conversation functionality."""
20+
print("🗣️ CONVERSATION DEMO")
21+
print("=" * 40)
22+
23+
routing_service = IntelligentRoutingService()
24+
25+
# Test different conversation types
26+
conversations = [
27+
"Hello",
28+
"How are you?",
29+
"What can you do?",
30+
"Thanks for your help",
31+
"Goodbye"
32+
]
33+
34+
for query in conversations:
35+
print(f"\nUser: {query}")
36+
response = routing_service.handle_conversation_query(query)
37+
print(f"Assistant: {response}")
38+
39+
print("\n" + "=" * 40)
40+
41+
42+
def demo_sql_generation():
43+
"""Demo SQL generation functionality."""
44+
print("🗃️ SQL GENERATION DEMO")
45+
print("=" * 40)
46+
47+
routing_service = IntelligentRoutingService()
48+
49+
# Test different SQL queries
50+
sql_queries = [
51+
"Show me all users",
52+
"Find customers who made purchases in the last 30 days",
53+
"Get the total sales by month",
54+
"SELECT * FROM users WHERE status = 'active'"
55+
]
56+
57+
for query in sql_queries:
58+
print(f"\nUser: {query}")
59+
response = routing_service.handle_sql_query(query, [])
60+
print(f"Assistant: {response[:200]}...")
61+
62+
print("\n" + "=" * 40)
63+
64+
65+
def demo_csv_analysis():
66+
"""Demo CSV analysis functionality."""
67+
print("📊 CSV ANALYSIS DEMO")
68+
print("=" * 40)
69+
70+
# Sample CSV data
71+
sample_csv = """name,age,salary,department
72+
Alice,25,50000,IT
73+
Bob,30,60000,HR
74+
Charlie,35,70000,IT
75+
Diana,28,55000,Finance
76+
Eve,32,65000,HR"""
77+
78+
print(f"Sample CSV Data:\n{sample_csv}")
79+
80+
routing_service = IntelligentRoutingService()
81+
82+
# Test different CSV analysis queries
83+
csv_queries = [
84+
"Show me the basic statistics of the data",
85+
"Create a bar chart of department distribution",
86+
"What is the average salary by department?",
87+
"Show me the top 3 highest paid employees"
88+
]
89+
90+
for query in csv_queries:
91+
print(f"\nUser: {query}")
92+
response = routing_service.handle_csv_query(query, sample_csv)
93+
print(f"Assistant: {response[:300]}...")
94+
95+
print("\n" + "=" * 40)
96+
97+
98+
def demo_intelligent_routing():
99+
"""Demo intelligent routing functionality."""
100+
print("🧠 INTELLIGENT ROUTING DEMO")
101+
print("=" * 40)
102+
103+
routing_service = IntelligentRoutingService()
104+
105+
# Test different types of queries
106+
test_queries = [
107+
("Hello", "CONVERSATION_AGENT"),
108+
("Show me all users", "SQL_AGENT"),
109+
("Analyze this CSV data", "CSV_AGENT"),
110+
("How are you?", "CONVERSATION_AGENT"),
111+
("SELECT * FROM users", "SQL_AGENT"),
112+
("Create a chart from the data", "CSV_AGENT")
113+
]
114+
115+
for query, expected_agent in test_queries:
116+
print(f"\nQuery: '{query}'")
117+
decision = routing_service.determine_agent(query, [], csv_loaded=True)
118+
print(f"Expected: {expected_agent}")
119+
print(f"Actual: {decision.agent}")
120+
print(f"Confidence: {decision.confidence}")
121+
print(f"Reasoning: {decision.reasoning}")
122+
123+
print("\n" + "=" * 40)
124+
125+
126+
def demo_orchestrator():
127+
"""Demo the main orchestrator functionality."""
128+
print("🎼 ORCHESTRATOR DEMO")
129+
print("=" * 40)
130+
131+
orchestrator = BackendOrchestrator()
132+
133+
# Create a new session
134+
session_info = orchestrator.create_new_session(NewChatRequest(session_name="Demo Session"))
135+
session_id = session_info.session_id
136+
print(f"Created session: {session_id}")
137+
138+
# Test different types of interactions
139+
interactions = [
140+
("Hello", "conversation"),
141+
("Show me all users", "sql"),
142+
("What can you do?", "conversation")
143+
]
144+
145+
for query, query_type in interactions:
146+
print(f"\nUser ({query_type}): {query}")
147+
response = orchestrator.generate_intelligent_response(session_id, query)
148+
print(f"Assistant: {response.content[:150]}...")
149+
150+
# Test CSV functionality
151+
sample_csv = "name,age,salary\nAlice,25,50000\nBob,30,60000\nCharlie,35,70000"
152+
result = orchestrator.load_csv_data(session_id, sample_csv)
153+
print(f"\nCSV Load Result: {result['status']}")
154+
155+
response = orchestrator.generate_intelligent_response(session_id, "Analyze this data")
156+
print(f"CSV Analysis: {response.content[:200]}...")
157+
158+
print("\n" + "=" * 40)
159+
160+
161+
def main():
162+
"""Run all demos."""
163+
print("🚀 Querypls Backend Functionality Demo")
164+
print("=" * 50)
165+
166+
demos = [
167+
("Conversation", demo_conversation),
168+
("SQL Generation", demo_sql_generation),
169+
("CSV Analysis", demo_csv_analysis),
170+
("Intelligent Routing", demo_intelligent_routing),
171+
("Orchestrator", demo_orchestrator),
172+
]
173+
174+
for demo_name, demo_func in demos:
175+
try:
176+
demo_func()
177+
except Exception as e:
178+
print(f"❌ {demo_name} demo failed: {str(e)}")
179+
180+
print("\n🎉 Demo completed! All backend functionality is working correctly.")
181+
print("\n📝 Summary:")
182+
print("- Conversation: Natural responses for greetings and help")
183+
print("- SQL Generation: Convert natural language to SQL queries")
184+
print("- CSV Analysis: Analyze CSV data with Python code")
185+
print("- Intelligent Routing: Automatically choose the right agent")
186+
print("- Orchestrator: Complete session management")
187+
188+
189+
if __name__ == "__main__":
190+
main()

src/backend/backend.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
Backend utilities for Streamlit configuration and styling.
33
"""
44

5-
from config.constants import STREAMLIT_CONFIG
5+
from src.config.constants import STREAMLIT_CONFIG
66
import streamlit as st
77
import sys
88
import os

src/backend/orchestrator.py

Lines changed: 15 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -7,33 +7,21 @@
77
from typing import List, Optional, Dict, Any
88
from dataclasses import dataclass
99

10-
from config.settings import get_settings
11-
from config.constants import (
12-
WELCOME_MESSAGE,
13-
DEFAULT_SESSION_NAME,
14-
CSV_LOAD_ERROR,
15-
CSV_ANALYSIS_ERROR,
16-
SESSION_CREATE_ERROR,
17-
ORCHESTRATOR_INIT_ERROR,
18-
SESSION_NOT_FOUND_ERROR,
19-
RESPONSE_GENERATION_ERROR,
20-
MESSAGE_LOAD_ERROR,
21-
MAX_CHAT_HISTORIES,
22-
)
23-
from services.sql_service import SQLGenerationService
24-
from services.csv_analysis_tools import CSVAnalysisTools, create_csv_analysis_agent
25-
from services.conversation_service import ConversationService
26-
from services.routing_service import IntelligentRoutingService
27-
from schemas.requests import (
10+
from src.config.settings import get_settings
11+
from src.config.constants import WELCOME_MESSAGE, DEFAULT_SESSION_NAME
12+
from src.services.sql_service import SQLGenerationService
13+
from src.services.csv_analysis_tools import CSVAnalysisTools, create_csv_analysis_agent
14+
from src.services.conversation_service import ConversationService
15+
from src.services.routing_service import IntelligentRoutingService
16+
from src.schemas.requests import (
2817
SQLGenerationRequest,
2918
ChatMessage,
3019
ConversationHistory,
3120
NewChatRequest,
3221
)
33-
from schemas.responses import (
22+
from src.schemas.responses import (
3423
ChatResponse,
3524
SessionInfo,
36-
ErrorResponse,
3725
HealthCheckResponse,
3826
)
3927

@@ -65,10 +53,8 @@ def create_new_session(self, request: NewChatRequest) -> SessionInfo:
6553

6654
messages = []
6755
if request.initial_context:
68-
messages.append(
69-
ChatMessage(
70-
role="system",
71-
content=request.initial_context))
56+
messages.append(ChatMessage(
57+
role="system", content=request.initial_context))
7258

7359
messages.append(ChatMessage(role="assistant", content=WELCOME_MESSAGE))
7460

@@ -113,8 +99,7 @@ def delete_session(self, session_id: str) -> bool:
11399
return True
114100
return False
115101

116-
def load_csv_data(self, session_id: str,
117-
csv_content: str) -> Dict[str, Any]:
102+
def load_csv_data(self, session_id: str, csv_content: str) -> Dict[str, Any]:
118103
session = self.get_session(session_id)
119104
if not session:
120105
raise ValueError(f"Session {session_id} not found")
@@ -134,9 +119,8 @@ def generate_intelligent_response(
134119
raise ValueError(f"Session {session_id} not found")
135120

136121
user_message = ChatMessage(
137-
role="user",
138-
content=user_query,
139-
timestamp=datetime.now().isoformat())
122+
role="user", content=user_query, timestamp=datetime.now().isoformat()
123+
)
140124
session.messages.append(user_message)
141125

142126
# Determine which agent should handle this query
@@ -157,7 +141,7 @@ def generate_intelligent_response(
157141
elif routing_decision.agent == "CSV_AGENT":
158142
if session.csv_data:
159143
response_content = self.routing_service.handle_csv_query(
160-
user_query, session.csv_data
144+
user_query, session.csv_data, session.messages
161145
)
162146
else:
163147
response_content = "I don't see any CSV data loaded. Please upload a CSV file first to analyze it."
@@ -187,9 +171,7 @@ def get_conversation_history(self, session_id: str) -> ConversationHistory:
187171
if not session:
188172
raise ValueError(f"Session {session_id} not found")
189173

190-
return ConversationHistory(
191-
messages=session.messages,
192-
session_id=session_id)
174+
return ConversationHistory(messages=session.messages, session_id=session_id)
193175

194176
def get_csv_info(self, session_id: str) -> Dict[str, Any]:
195177
return self.csv_tools.get_csv_info(session_id)

src/config/constants.py

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,41 @@
1010
STREAMLIT_HOST = "localhost"
1111

1212
# Streamlit Configuration
13-
STREAMLIT_CONFIG = {
14-
"page_title": "Querypls",
15-
"page_icon": "💬",
16-
"layout": "wide"}
13+
STREAMLIT_CONFIG = {"page_title": "Querypls",
14+
"page_icon": "💬", "layout": "wide"}
15+
16+
# Welcome and Session Messages
17+
WELCOME_MESSAGE = "Hello! 👋 I'm Querypls, your SQL and data analysis assistant. I can help you generate SQL queries or analyze CSV files. What would you like to work on today?"
18+
DEFAULT_SESSION_NAME = "Default Chat"
19+
20+
# CSV Analysis Section
21+
CSV_ANALYSIS_SECTION = "### 📊 CSV Analysis"
22+
CSV_UPLOAD_LABEL = "Upload CSV File"
23+
CSV_UPLOAD_HELP = "Upload a CSV file to analyze with Python code"
24+
CSV_PREVIEW = "📋 CSV Preview"
25+
CSV_COLUMNS = "**Columns:** {columns}"
26+
CSV_DTYPES = "**Data Types:** {dtypes}"
27+
LOAD_CSV_BUTTON = "📊 Load CSV Data"
28+
CSV_LOADED_SUCCESS = "✅ CSV data loaded successfully!"
29+
CSV_UPLOAD_SUCCESS = "✅ CSV uploaded successfully! Shape: {shape}"
30+
CSV_UPLOAD_ERROR = "❌ Error uploading CSV: {error}"
31+
CSV_LOAD_ERROR = "❌ No CSV data loaded. Please upload a CSV file first."
32+
CSV_ANALYSIS_ERROR = "❌ Error analyzing CSV: {error}"
33+
34+
# Session Management
35+
SESSIONS_SECTION = "### 💬 Chat Sessions"
36+
NEW_SESSION_BUTTON = "➕ New Session"
37+
SESSION_CREATE_ERROR = "❌ Error creating session: {error}"
38+
SESSION_NOT_FOUND_ERROR = "❌ Session not found"
39+
40+
# Application Errors
41+
ORCHESTRATOR_INIT_ERROR = "❌ Error initializing orchestrator: {error}"
42+
APP_INIT_ERROR = "❌ Error initializing application"
43+
RESPONSE_GENERATION_ERROR = "❌ Error generating response: {error}"
44+
MESSAGE_LOAD_ERROR = "❌ Error loading messages: {error}"
45+
46+
# UI Elements
47+
MADE_WITH_LOVE = "Made with 🤍"
1748

1849
# Available Models
1950
AVAILABLE_MODELS = {

src/config/settings.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,7 @@
1313
class Settings(BaseSettings):
1414
groq_api_key: str = Field(..., env="GROQ_API_KEY")
1515
groq_model_name: str = Field(
16-
default="openai/gpt-oss-120b",
17-
env="GROQ_MODEL_NAME")
16+
default="openai/gpt-oss-120b", env="GROQ_MODEL_NAME")
1817
app_version: str = Field(default="1.0.0", env="APP_VERSION")
1918
max_chat_histories: int = Field(default=5, env="MAX_CHAT_HISTORIES")
2019
debug_mode: bool = Field(default=False, env="DEBUG_MODE")

0 commit comments

Comments
 (0)