dvwn commited on
Commit
edef444
·
1 Parent(s): 8c0edc5

Update Agent Response using NL

Browse files
app/main.py CHANGED
@@ -2,8 +2,8 @@
2
  # Main entry point for the NL2SQL application
3
  import os
4
  from dotenv import load_dotenv
5
- from src.nl2sql.sql_agent import nl2sql_agent
6
- from src.scripts.evaluate_hf import run_evaluation
7
 
8
  load_dotenv()
9
  # Load HuggingFace API token from environment variable
@@ -11,32 +11,6 @@ hf_token = os.getenv("HF_TOKEN")
11
  if not hf_token:
12
  raise ValueError("HuggingFace API token not found!")
13
 
14
- # User prompt question manually and see the agent's response
15
- def interactive_mode():
16
- """Allows user to manually type questions and get agent's response."""
17
- print("\n========= Interactive NL2SQL Mode =========")
18
- print("Type 'exit' or 'q' to return to the main menu.\n")
19
-
20
- while True:
21
- question = input("\nEnter your question: ")
22
- if question.lower() in ['exit', 'q']:
23
- break
24
- if not question.strip():
25
- continue
26
-
27
- print("\nProcessing your question...")
28
- response = nl2sql_agent(question)
29
-
30
- print("\n========= Agent Response =========")
31
- print(f"Status: {response.get('status')}")
32
- print(f"Generated SQL:\n{response.get('query')}")
33
-
34
- if response.get('status') == 'success':
35
- print(f"\nresults (First 5 rows):\n{response.get('results')[:5]}")
36
- else:
37
- print(f"\nError Details:\n{response.get('error')}")
38
- print("==================================\n")
39
-
40
  def main():
41
  """Main application entry point and interactive menu"""
42
  while True:
@@ -51,7 +25,7 @@ def main():
51
  choice = input("Select an option (1-3): ")
52
 
53
  if choice == '1':
54
- interactive_mode()
55
  elif choice == '2':
56
  run_evaluation()
57
  elif choice == '3':
 
2
  # Main entry point for the NL2SQL application
3
  import os
4
  from dotenv import load_dotenv
5
+ from src.scripts.interactive_mode import run_interactiveMode
6
+ from src.scripts.evaluation_mode import run_evaluation
7
 
8
  load_dotenv()
9
  # Load HuggingFace API token from environment variable
 
11
  if not hf_token:
12
  raise ValueError("HuggingFace API token not found!")
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def main():
15
  """Main application entry point and interactive menu"""
16
  while True:
 
25
  choice = input("Select an option (1-3): ")
26
 
27
  if choice == '1':
28
+ run_interactiveMode()
29
  elif choice == '2':
30
  run_evaluation()
31
  elif choice == '3':
src/nl2sql/sql_agent.py CHANGED
@@ -40,6 +40,16 @@ Do not include any explanations, markdown formatting, or code blocks.
40
 
41
  Corrected SQL Query:"""
42
 
 
 
 
 
 
 
 
 
 
 
43
  prompt_template = PromptTemplate(
44
  input_variables = ["schema", "question"],
45
  template = SQL_PROMPT_TEMPLATE
@@ -50,6 +60,11 @@ refinement_prompt = PromptTemplate(
50
  template = REFINEMENT_PROMPT_TEMPLATE
51
  )
52
 
 
 
 
 
 
53
  # Clean the output
54
  def clean_sql(raw_sql: str) -> str:
55
  """
@@ -83,6 +98,7 @@ def nl2sql_agent(user_question: str, max_retries: int = 3) -> dict:
83
  # LangChain Pipeline: Pipe prompt into LLM
84
  chain = prompt_template | llm
85
  refinement_chain = refinement_prompt | llm
 
86
 
87
  current_sql = ""
88
  error_message = ""
@@ -126,10 +142,18 @@ def nl2sql_agent(user_question: str, max_retries: int = 3) -> dict:
126
 
127
  if attempt > 1:
128
  print(f"SQL query executed successfully after {attempt} attempts.")
 
 
 
 
 
 
 
129
 
130
  return {
131
  "query": generated_sql,
132
  "results": results,
 
133
  "status": "success",
134
  "attempts": attempt
135
  }
 
40
 
41
  Corrected SQL Query:"""
42
 
43
+ # Generate text response
44
+ NL_RESPONSE_TEMPLATE = """You are a helpful data assisstant.
45
+ The user asked the following question: "{question}"
46
+ The database returned the following results: {results}
47
+
48
+ Provide a direct, natural language answer to the user's question using ONLY the provided data.
49
+ Keep it brief. Do not explain the SQL query or mention the database schema.
50
+
51
+ Answer:"""
52
+
53
  prompt_template = PromptTemplate(
54
  input_variables = ["schema", "question"],
55
  template = SQL_PROMPT_TEMPLATE
 
60
  template = REFINEMENT_PROMPT_TEMPLATE
61
  )
62
 
63
+ nl_response_template = PromptTemplate(
64
+ input_variables = ["question", "results"],
65
+ template = NL_RESPONSE_TEMPLATE
66
+ )
67
+
68
  # Clean the output
69
  def clean_sql(raw_sql: str) -> str:
70
  """
 
98
  # LangChain Pipeline: Pipe prompt into LLM
99
  chain = prompt_template | llm
100
  refinement_chain = refinement_prompt | llm
101
+ nl_chain = nl_response_template | llm
102
 
103
  current_sql = ""
104
  error_message = ""
 
142
 
143
  if attempt > 1:
144
  print(f"SQL query executed successfully after {attempt} attempts.")
145
+
146
+ # Generate natural language response based on the results
147
+ print("Generating natural language response based on query results...")
148
+ nl_response = nl_chain.invoke({
149
+ "question": user_question,
150
+ "results": str(results)
151
+ })
152
 
153
  return {
154
  "query": generated_sql,
155
  "results": results,
156
+ "nl_response": nl_response,
157
  "status": "success",
158
  "attempts": attempt
159
  }
src/scripts/evaluation_mode.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path: src/scripts/evaluation_mode.py
2
+ # Evaluation script for Hugging Face SQL generation.
3
+ import json
4
+ from pathlib import Path
5
+ import pandas as pd
6
+ from src.database.db_manager import get_db_connection
7
+ from src.nl2sql.sql_agent import nl2sql_agent
8
+
9
+ TEST_CASES_PATH = Path("src/scripts/test_cases.json")
10
+ RESULTS_PATH = Path("hf_evaluation_results.json")
11
+
12
+ def _normalize_dataframe(dataframe: pd.DataFrame) -> pd.DataFrame:
13
+ # Normalize dataframe to ensure accurate comparison
14
+ normalized = dataframe.copy()
15
+ normalized.columns = [str(column).lower() for column in normalized.columns]
16
+
17
+ for column in normalized.columns:
18
+ normalized[column] = normalized[column].map(
19
+ lambda value: round(float(value), 6)
20
+ if isinstance(value, float)
21
+ else value
22
+ )
23
+
24
+ sort_columns = list(normalized.columns)
25
+ if sort_columns:
26
+ normalized = normalized.sort_values(by=sort_columns, kind="mergesort").reset_index(drop=True)
27
+
28
+ return normalized
29
+
30
+ # Compare generated SQL results with expected results
31
+ def compare_results(df_generated: pd.DataFrame, df_gold: pd.DataFrame) -> bool:
32
+ """Compare generated and expected query results."""
33
+ if df_generated is None or df_gold is None:
34
+ return False
35
+
36
+ try:
37
+ normalized_generated = _normalize_dataframe(df_generated)
38
+ normalized_gold = _normalize_dataframe(df_gold)
39
+ return normalized_generated.equals(normalized_gold)
40
+ except Exception as error:
41
+ print(f"Error comparing results: {error}")
42
+ return False
43
+
44
+ def run_evaluation():
45
+ if not TEST_CASES_PATH.exists():
46
+ print(f"Error: Could not find test cases at {TEST_CASES_PATH}")
47
+ return
48
+
49
+ with TEST_CASES_PATH.open("r", encoding="utf-8") as handle:
50
+ test_cases = json.load(handle)
51
+
52
+ results = []
53
+ correct_count = 0
54
+
55
+ print(f"Running evaluation on {len(test_cases)} test cases...\n")
56
+
57
+ for case in test_cases:
58
+ question = case["question"]
59
+ print(f"Testing ID {case['id']}: {question[:50]}...")
60
+
61
+ # Implement agent to handle RAG retrieval and SQL generation
62
+ agent_response = nl2sql_agent(user_question=question)
63
+ generated_sql = agent_response.get("query", "")
64
+
65
+ connection = get_db_connection()
66
+ if connection is None:
67
+ raise RuntimeError("Unable to connect to the SQLite database.")
68
+
69
+ try:
70
+ df_generated = pd.read_sql_query(generated_sql, connection)
71
+ df_gold = pd.read_sql_query(case["gold_sql"], connection)
72
+
73
+ is_correct = compare_results(df_generated, df_gold)
74
+ if is_correct:
75
+ correct_count += 1
76
+
77
+ results.append(
78
+ {
79
+ "id": case["id"],
80
+ "question": question,
81
+ "status": "PASS" if is_correct else "FAIL",
82
+ "generated_sql": generated_sql,
83
+ "gold_sql": case["gold_sql"],
84
+ }
85
+ )
86
+ except Exception as error:
87
+ results.append(
88
+ {
89
+ "id": case["id"],
90
+ "question": question,
91
+ "status": "ERROR",
92
+ "generated_sql": generated_sql,
93
+ "gold_sql": case["gold_sql"],
94
+ "error": str(error),
95
+ }
96
+ )
97
+ finally:
98
+ connection.close()
99
+
100
+ accuracy = (correct_count / len(test_cases)) * 100 if test_cases else 0.0
101
+ print("\nEVALUATION COMPLETE")
102
+ print(f"Total Test Cases: {len(test_cases)}")
103
+ print(f"Correctly Generated SQL: {correct_count} / {len(test_cases)}")
104
+ print(f"Execution Accuracy: {accuracy:.2f}%")
105
+
106
+ with RESULTS_PATH.open("w", encoding="utf-8") as handle:
107
+ json.dump(results, handle, indent=4)
src/scripts/interactive_mode.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Path: src/scripts/interactive_mode.py
2
+ # Interactive mode: Allows user to manually type questions and see the agent's response
3
+ from src.nl2sql.sql_agent import nl2sql_agent
4
+
5
+ def run_interactiveMode():
6
+ """ Allows user to manually type questions and get agent's response."""
7
+ print("\n========= Interactive NL2SQL Mode =========")
8
+ print("Type 'exit' or 'q' to return to the main menu.\n")
9
+
10
+ while True:
11
+ question = input("\nEnter your question: ")
12
+ if question.lower() in ['exit', 'q']:
13
+ break
14
+ if not question.strip():
15
+ continue
16
+
17
+ print("\nProcessing your question...")
18
+ response = nl2sql_agent(question)
19
+
20
+ print("\n========= Agent Response =========")
21
+ if response.get('status') == 'success':
22
+ print(f"Answer: {response.get('nl_response')}\n")
23
+ print(f"Generated SQL:\n{response.get('query')}\n")
24
+ else:
25
+ print(f"Status: {response.get('status')}")
26
+ print(f"Generated SQL:\n{response.get('query')}")
27
+ print(f"\nError Details:\n{response.get('error')}")
28
+ print("==================================\n")