dvwn commited on
Commit
9f8f0ff
·
1 Parent(s): d9b3c34

Update Agent response in NL

Browse files

1. Update main.py to separate the interactive logic keeping it modular.
2. Create new file (interactive_mode.py) to handle conversational mode.
3. Update sql_agent.py to include NL response template so system return NL response to user with data needed instead of only generated SQL.
4. Update evaluate_hf.py -> evaluation_mode.py to make naming convention consistent.

.vscode/settings.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "postman.settings.dotenv-detection-notification-visibility": false
3
+ }
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':
freeze DELETED
File without changes
src/database/__pycache__/db_manager.cpython-313.pyc CHANGED
Binary files a/src/database/__pycache__/db_manager.cpython-313.pyc and b/src/database/__pycache__/db_manager.cpython-313.pyc differ
 
src/nl2sql/__pycache__/hf_engine.cpython-313.pyc CHANGED
Binary files a/src/nl2sql/__pycache__/hf_engine.cpython-313.pyc and b/src/nl2sql/__pycache__/hf_engine.cpython-313.pyc differ
 
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/__pycache__/evaluate_hf.cpython-313.pyc CHANGED
Binary files a/src/scripts/__pycache__/evaluate_hf.cpython-313.pyc and b/src/scripts/__pycache__/evaluate_hf.cpython-313.pyc differ
 
src/scripts/{evaluate_hf.py → evaluation_mode.py} RENAMED
@@ -1,6 +1,5 @@
1
- # src/scripts/evaluate_hf.py
2
  # Evaluation script for Hugging Face SQL generation.
3
-
4
  import json
5
  from pathlib import Path
6
  import pandas as pd
 
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
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")