velmurugan1122 commited on
Commit
ef854f8
·
verified ·
1 Parent(s): 89ced8b

Upload testfile.py

Browse files
Files changed (1) hide show
  1. back_end/application/testfile.py +16 -23
back_end/application/testfile.py CHANGED
@@ -1,15 +1,7 @@
1
  import os
2
  import sqlite3
3
- import logging
4
  from groq import Groq
5
 
6
- # Configure logging
7
- logging.basicConfig(
8
- filename="healthcare_chatbot.log",
9
- level=logging.INFO,
10
- format="%(asctime)s - %(levelname)s - %(message)s"
11
- )
12
-
13
  # Load Groq API key from environment variable
14
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
15
 
@@ -65,11 +57,9 @@ def get_sql_query(natural_language_query):
65
  model="llama3-8b-8192",
66
  temperature=0
67
  )
68
- sql_query = completion.choices[0].message.content.strip()
69
- logging.info(f"Generated SQL Query: {sql_query}")
70
- return sql_query
71
  except Exception as e:
72
- logging.error(f"Error generating SQL query: {str(e)}")
73
  return f"Error generating SQL query: {str(e)}"
74
 
75
  # Function to execute the SQL query
@@ -80,27 +70,29 @@ def execute_sql_query(sql_query):
80
  database = "veludb.db" # Ensure this is the correct database
81
 
82
  try:
83
- logging.info(f"Executing query: {sql_query}")
84
  conn = sqlite3.connect(database)
85
  cursor = conn.cursor()
86
  cursor.execute(sql_query)
87
  rows = cursor.fetchall()
 
 
88
  columns = [desc[0] for desc in cursor.description] if cursor.description else []
 
89
  conn.close()
90
 
91
  if not rows:
92
- logging.info("No matching records found.")
93
  return {"status": "success", "data": "No matching records found."}
94
 
 
95
  if "COUNT" in sql_query.upper():
96
- logging.info(f"Count query result: {rows[0][0]}")
97
  return {"status": "success", "data": f"There are {rows[0][0]} matching records."}
98
 
 
99
  formatted_data = [dict(zip(columns, row)) for row in rows]
100
- logging.info(f"Query executed successfully, returned {len(rows)} rows.")
101
  return {"status": "success", "data": formatted_data}
 
102
  except Exception as e:
103
- logging.error(f"Query execution failed: {str(e)}")
104
  return {"status": "error", "message": f"Query execution failed: {str(e)}"}
105
 
106
  # Function to refine the response using another LLM
@@ -129,23 +121,24 @@ def refine_response(user_query, sql_data):
129
  model="llama3-8b-8192",
130
  temperature=0
131
  )
132
- refined_response = completion.choices[0].message.content.strip()
133
- logging.info(f"Refined response: {refined_response}")
134
- return refined_response
135
  except Exception as e:
136
- logging.error(f"Error refining response: {str(e)}")
137
  return f"Error refining response: {str(e)}"
138
 
139
  # Example Usage
140
  if __name__ == "__main__":
 
141
  user_query = "How many male patients are there?"
142
- logging.info(f"User Query: {user_query}")
143
 
 
144
  sql_query = get_sql_query(user_query)
145
  print("Generated SQL Query:\n", sql_query)
146
 
 
147
  query_result = execute_sql_query(sql_query)
148
  print("Query Result:\n", query_result)
149
 
150
- refined_response = refine_response(user_query, query_result["data"])
 
151
  print("Refined Response:\n", refined_response)
 
1
  import os
2
  import sqlite3
 
3
  from groq import Groq
4
 
 
 
 
 
 
 
 
5
  # Load Groq API key from environment variable
6
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
7
 
 
57
  model="llama3-8b-8192",
58
  temperature=0
59
  )
60
+ return completion.choices[0].message.content.strip()
61
+
 
62
  except Exception as e:
 
63
  return f"Error generating SQL query: {str(e)}"
64
 
65
  # Function to execute the SQL query
 
70
  database = "veludb.db" # Ensure this is the correct database
71
 
72
  try:
73
+ # print("Executing query")
74
  conn = sqlite3.connect(database)
75
  cursor = conn.cursor()
76
  cursor.execute(sql_query)
77
  rows = cursor.fetchall()
78
+ # print("Successfully Executing query")
79
+ # Extract column names
80
  columns = [desc[0] for desc in cursor.description] if cursor.description else []
81
+
82
  conn.close()
83
 
84
  if not rows:
 
85
  return {"status": "success", "data": "No matching records found."}
86
 
87
+ # If the query is a COUNT query, extract the number directly
88
  if "COUNT" in sql_query.upper():
 
89
  return {"status": "success", "data": f"There are {rows[0][0]} matching records."}
90
 
91
+ # Format the data output
92
  formatted_data = [dict(zip(columns, row)) for row in rows]
 
93
  return {"status": "success", "data": formatted_data}
94
+
95
  except Exception as e:
 
96
  return {"status": "error", "message": f"Query execution failed: {str(e)}"}
97
 
98
  # Function to refine the response using another LLM
 
121
  model="llama3-8b-8192",
122
  temperature=0
123
  )
124
+ return completion.choices[0].message.content.strip()
125
+
 
126
  except Exception as e:
 
127
  return f"Error refining response: {str(e)}"
128
 
129
  # Example Usage
130
  if __name__ == "__main__":
131
+ # Example user query
132
  user_query = "How many male patients are there?"
 
133
 
134
+ # Step 1: Convert natural language query to SQL
135
  sql_query = get_sql_query(user_query)
136
  print("Generated SQL Query:\n", sql_query)
137
 
138
+ # Step 2: Execute SQL query and fetch results
139
  query_result = execute_sql_query(sql_query)
140
  print("Query Result:\n", query_result)
141
 
142
+ # Step 3: Refine the response using another LLM
143
+ refined_response = refine_response(user_query, sql_query, query_result["data"])
144
  print("Refined Response:\n", refined_response)