timeki commited on
Commit
7287f1d
·
2 Parent(s): 6e717b7 668db15

Merge branch 'featue/add_ttd' into dev

Browse files
.gitignore CHANGED
@@ -12,6 +12,8 @@ notebooks/
12
  data/
13
  sandbox/
14
 
 
15
  *.db
 
16
  data_ingestion/
17
- .vscode
 
12
  data/
13
  sandbox/
14
 
15
+ climateqa/talk_to_data/database/
16
  *.db
17
+
18
  data_ingestion/
19
+ .vscode
app.py CHANGED
@@ -12,6 +12,7 @@ from climateqa.engine.reranker import get_reranker
12
  from climateqa.engine.graph import make_graph_agent,make_graph_agent_poc
13
  from climateqa.engine.chains.retrieve_papers import find_papers
14
  from climateqa.chat import start_chat, chat_stream, finish_chat
 
15
 
16
  from front.tabs import (create_config_modal, create_examples_tab, create_papers_tab, create_figures_tab, create_chat_interface, create_about_tab)
17
  from front.utils import process_figures
@@ -150,6 +151,10 @@ def cqa_tab(tab_name):
150
  "<h2>There are no graphs to be displayed at the moment. Try asking another question.</h2>",
151
  elem_id="graphs-container"
152
  )
 
 
 
 
153
  return {
154
  "chatbot": chatbot,
155
  "textbox": textbox,
@@ -170,7 +175,9 @@ def cqa_tab(tab_name):
170
  "tab_figures": tab_figures,
171
  "tab_graphs": tab_graphs,
172
  "tab_papers": tab_papers,
173
- "graph_container": graphs_container
 
 
174
  }
175
 
176
 
@@ -200,6 +207,9 @@ def event_handling(
200
  tab_graphs = main_tab_components["tab_graphs"]
201
  tab_papers = main_tab_components["tab_papers"]
202
  graphs_container = main_tab_components["graph_container"]
 
 
 
203
 
204
  config_open = config_components["config_open"]
205
  config_modal = config_components["config_modal"]
@@ -214,8 +224,8 @@ def event_handling(
214
  close_config_modal = config_components["close_config_modal_button"]
215
 
216
  new_sources_hmtl = gr.State([])
217
-
218
- print("textbox id : ", textbox.elem_id)
219
 
220
  for button in [config_button, close_config_modal]:
221
  button.click(
@@ -271,6 +281,9 @@ def event_handling(
271
 
272
 
273
 
 
 
 
274
  def main_ui():
275
  # config_open = gr.State(True)
276
  with gr.Blocks(title="Climate Q&A", css_paths=os.getcwd()+ "/style.css", theme=theme, elem_id="main-component") as demo:
 
12
  from climateqa.engine.graph import make_graph_agent,make_graph_agent_poc
13
  from climateqa.engine.chains.retrieve_papers import find_papers
14
  from climateqa.chat import start_chat, chat_stream, finish_chat
15
+ from climateqa.engine.talk_to_data.main import ask_vanna
16
 
17
  from front.tabs import (create_config_modal, create_examples_tab, create_papers_tab, create_figures_tab, create_chat_interface, create_about_tab)
18
  from front.utils import process_figures
 
151
  "<h2>There are no graphs to be displayed at the moment. Try asking another question.</h2>",
152
  elem_id="graphs-container"
153
  )
154
+ with gr.Tab("DRIAS", elem_id="tab-vanna", id=6) as tab_vanna:
155
+ vanna_table = gr.DataFrame([], elem_id="vanna-display")
156
+ vanna_display = gr.Plot()
157
+
158
  return {
159
  "chatbot": chatbot,
160
  "textbox": textbox,
 
175
  "tab_figures": tab_figures,
176
  "tab_graphs": tab_graphs,
177
  "tab_papers": tab_papers,
178
+ "graph_container": graphs_container,
179
+ "vanna_table" : vanna_table,
180
+ "vanna_display": vanna_display
181
  }
182
 
183
 
 
207
  tab_graphs = main_tab_components["tab_graphs"]
208
  tab_papers = main_tab_components["tab_papers"]
209
  graphs_container = main_tab_components["graph_container"]
210
+ vanna_table = main_tab_components["vanna_table"]
211
+ vanna_display = main_tab_components["vanna_display"]
212
+
213
 
214
  config_open = config_components["config_open"]
215
  config_modal = config_components["config_modal"]
 
224
  close_config_modal = config_components["close_config_modal_button"]
225
 
226
  new_sources_hmtl = gr.State([])
227
+ ttd_data = gr.State([])
228
+
229
 
230
  for button in [config_button, close_config_modal]:
231
  button.click(
 
281
 
282
 
283
 
284
+ # Drias search
285
+ textbox.submit(ask_vanna, [textbox], [vanna_table, vanna_display])
286
+
287
  def main_ui():
288
  # config_open = gr.State(True)
289
  with gr.Blocks(title="Climate Q&A", css_paths=os.getcwd()+ "/style.css", theme=theme, elem_id="main-component") as demo:
climateqa/chat.py CHANGED
@@ -53,6 +53,13 @@ def log_interaction_to_azure(history, output_query, sources, docs, share_client,
53
  print(f"Error logging on Azure Blob Storage: {e}")
54
  error_msg = f"ClimateQ&A Error: {str(e)[:100]} - The error has been noted, try another question and if the error remains, you can contact us :)"
55
  raise gr.Error(error_msg)
 
 
 
 
 
 
 
56
 
57
  # Main chat function
58
  async def chat_stream(
@@ -121,6 +128,7 @@ async def chat_stream(
121
  used_documents = []
122
  retrieved_contents = []
123
  answer_message_content = ""
 
124
 
125
  # Define processing steps
126
  steps_display = {
@@ -142,6 +150,14 @@ async def chat_stream(
142
  history, used_documents, retrieved_contents = handle_retrieved_documents(
143
  event, history, used_documents, retrieved_contents
144
  )
 
 
 
 
 
 
 
 
145
  if event["event"] == "on_chain_end" and event["name"] == "answer_search" :
146
  docs = event["data"]["input"]["documents"]
147
  docs_html = convert_to_docs_to_html(docs)
@@ -184,7 +200,7 @@ async def chat_stream(
184
  sub_questions = [q["question"] + "-> relevant sources : " + str(q["sources"]) for q in event["data"]["output"]["questions_list"]]
185
  history[-1].content += "Decompose question into sub-questions:\n\n - " + "\n - ".join(sub_questions)
186
 
187
- yield history, docs_html, output_query, output_language, related_contents, graphs_html
188
 
189
  except Exception as e:
190
  print(f"Event {event} has failed")
@@ -195,4 +211,4 @@ async def chat_stream(
195
  # Call the function to log interaction
196
  log_interaction_to_azure(history, output_query, sources, docs, share_client, user_id)
197
 
198
- yield history, docs_html, output_query, output_language, related_contents, graphs_html
 
53
  print(f"Error logging on Azure Blob Storage: {e}")
54
  error_msg = f"ClimateQ&A Error: {str(e)[:100]} - The error has been noted, try another question and if the error remains, you can contact us :)"
55
  raise gr.Error(error_msg)
56
+
57
+ def handle_numerical_data(event):
58
+ if event["name"] == "retrieve_drias_data" and event["event"] == "on_chain_end":
59
+ numerical_data = event["data"]["output"]["drias_data"]
60
+ sql_query = event["data"]["output"]["drias_sql_query"]
61
+ return numerical_data, sql_query
62
+ return None, None
63
 
64
  # Main chat function
65
  async def chat_stream(
 
128
  used_documents = []
129
  retrieved_contents = []
130
  answer_message_content = ""
131
+ vanna_data = {}
132
 
133
  # Define processing steps
134
  steps_display = {
 
150
  history, used_documents, retrieved_contents = handle_retrieved_documents(
151
  event, history, used_documents, retrieved_contents
152
  )
153
+ # Handle Vanna retrieval
154
+ # if event["event"] == "on_chain_end" and event["name"] in ["retrieve_documents","retrieve_local_data"] and event["data"]["output"] != None:
155
+ # df_output_vanna, sql_query = handle_numerical_data(
156
+ # event
157
+ # )
158
+ # vanna_data = {"df_output": df_output_vanna, "sql_query": sql_query}
159
+
160
+
161
  if event["event"] == "on_chain_end" and event["name"] == "answer_search" :
162
  docs = event["data"]["input"]["documents"]
163
  docs_html = convert_to_docs_to_html(docs)
 
200
  sub_questions = [q["question"] + "-> relevant sources : " + str(q["sources"]) for q in event["data"]["output"]["questions_list"]]
201
  history[-1].content += "Decompose question into sub-questions:\n\n - " + "\n - ".join(sub_questions)
202
 
203
+ yield history, docs_html, output_query, output_language, related_contents, graphs_html#, vanna_data
204
 
205
  except Exception as e:
206
  print(f"Event {event} has failed")
 
211
  # Call the function to log interaction
212
  log_interaction_to_azure(history, output_query, sources, docs, share_client, user_id)
213
 
214
+ yield history, docs_html, output_query, output_language, related_contents, graphs_html#, vanna_data
climateqa/engine/chains/drias_retriever.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ from climateqa.engine.talk_to_data.main import ask_vanna
4
+
5
+
6
+ def make_drias_retriever_node(llm):
7
+
8
+ def retrieve_drias_data(state):
9
+ print("---- Retrieving data from DRIAS ----")
10
+ query = state["query"]
11
+ sql_query, df = ask_vanna(query)
12
+ state["drias_data"] = df
13
+ state["drias_sql_query"] = sql_query
14
+ return state
15
+
16
+ return retrieve_drias_data
climateqa/engine/chains/intent_categorization.py CHANGED
@@ -57,6 +57,7 @@ def make_intent_categorization_node(llm):
57
  categorization_chain = make_intent_categorization_chain(llm)
58
 
59
  def categorize_message(state):
 
60
  print("---- Categorize_message ----")
61
 
62
  output = categorization_chain.invoke({"input": state["user_input"]})
 
57
  categorization_chain = make_intent_categorization_chain(llm)
58
 
59
  def categorize_message(state):
60
+ print("Input Message : ", state["user_input"])
61
  print("---- Categorize_message ----")
62
 
63
  output = categorization_chain.invoke({"input": state["user_input"]})
climateqa/engine/chains/query_transformation.py CHANGED
@@ -293,6 +293,8 @@ def make_query_transform_node(llm,k_final=15):
293
  "n_questions":n_questions,
294
  "handled_questions_index":[],
295
  }
 
 
296
  return new_state
297
 
298
  return transform_query
 
293
  "n_questions":n_questions,
294
  "handled_questions_index":[],
295
  }
296
+ print("New questions")
297
+ print(new_questions)
298
  return new_state
299
 
300
  return transform_query
climateqa/engine/graph.py CHANGED
@@ -11,7 +11,7 @@ from typing import List, Dict
11
 
12
  import operator
13
  from typing import Annotated
14
-
15
  from IPython.display import display, HTML, Image
16
 
17
  from .chains.answer_chitchat import make_chitchat_node
@@ -23,6 +23,7 @@ from .chains.retrieve_documents import make_IPx_retriever_node, make_POC_retriev
23
  from .chains.answer_rag import make_rag_node
24
  from .chains.graph_retriever import make_graph_retriever_node
25
  from .chains.chitchat_categorization import make_chitchat_intent_categorization_node
 
26
  # from .chains.set_defaults import set_defaults
27
 
28
  class GraphState(TypedDict):
@@ -49,6 +50,8 @@ class GraphState(TypedDict):
49
  recommended_content : List[Document] # OWID Graphs # TODO merge with related_contents
50
  search_only : bool = False
51
  reports : List[str] = []
 
 
52
 
53
  def dummy(state):
54
  return
@@ -72,7 +75,7 @@ def route_intent(state):
72
  def chitchat_route_intent(state):
73
  intent = state["search_graphs_chitchat"]
74
  if intent is True:
75
- return "retrieve_graphs_chitchat"
76
  elif intent is False:
77
  return END
78
 
@@ -224,6 +227,7 @@ def make_graph_agent_poc(llm, vectorstore_ipcc, vectorstore_graphs, vectorstore_
224
  answer_rag = make_rag_node(llm, with_docs=True)
225
  answer_rag_no_docs = make_rag_node(llm, with_docs=False)
226
  chitchat_categorize_intent = make_chitchat_intent_categorization_node(llm)
 
227
 
228
  # Define the nodes
229
  # workflow.add_node("set_defaults", set_defaults)
@@ -242,6 +246,7 @@ def make_graph_agent_poc(llm, vectorstore_ipcc, vectorstore_graphs, vectorstore_
242
  workflow.add_node("retrieve_documents", retrieve_documents)
243
  workflow.add_node("answer_rag", answer_rag)
244
  workflow.add_node("answer_rag_no_docs", answer_rag_no_docs)
 
245
 
246
  # Entry point
247
  workflow.set_entry_point("categorize_intent")
@@ -291,6 +296,10 @@ def make_graph_agent_poc(llm, vectorstore_ipcc, vectorstore_graphs, vectorstore_
291
  workflow.add_edge("retrieve_local_data", "answer_search")
292
  workflow.add_edge("retrieve_documents", "answer_search")
293
 
 
 
 
 
294
  # Compile
295
  app = workflow.compile()
296
  return app
 
11
 
12
  import operator
13
  from typing import Annotated
14
+ import pandas as pd
15
  from IPython.display import display, HTML, Image
16
 
17
  from .chains.answer_chitchat import make_chitchat_node
 
23
  from .chains.answer_rag import make_rag_node
24
  from .chains.graph_retriever import make_graph_retriever_node
25
  from .chains.chitchat_categorization import make_chitchat_intent_categorization_node
26
+ from .chains.drias_retriever import make_drias_retriever_node
27
  # from .chains.set_defaults import set_defaults
28
 
29
  class GraphState(TypedDict):
 
50
  recommended_content : List[Document] # OWID Graphs # TODO merge with related_contents
51
  search_only : bool = False
52
  reports : List[str] = []
53
+ drias_data: pd.DataFrame
54
+ drias_sql_query : str
55
 
56
  def dummy(state):
57
  return
 
75
  def chitchat_route_intent(state):
76
  intent = state["search_graphs_chitchat"]
77
  if intent is True:
78
+ return END #TODO
79
  elif intent is False:
80
  return END
81
 
 
227
  answer_rag = make_rag_node(llm, with_docs=True)
228
  answer_rag_no_docs = make_rag_node(llm, with_docs=False)
229
  chitchat_categorize_intent = make_chitchat_intent_categorization_node(llm)
230
+ retrieve_drias_data = make_drias_retriever_node(llm)
231
 
232
  # Define the nodes
233
  # workflow.add_node("set_defaults", set_defaults)
 
246
  workflow.add_node("retrieve_documents", retrieve_documents)
247
  workflow.add_node("answer_rag", answer_rag)
248
  workflow.add_node("answer_rag_no_docs", answer_rag_no_docs)
249
+ workflow.add_node("retrieve_drias_data", retrieve_drias_data)
250
 
251
  # Entry point
252
  workflow.set_entry_point("categorize_intent")
 
296
  workflow.add_edge("retrieve_local_data", "answer_search")
297
  workflow.add_edge("retrieve_documents", "answer_search")
298
 
299
+ workflow.add_edge("transform_query", "retrieve_drias_data")
300
+ workflow.add_edge("retrieve_drias_data", END)
301
+
302
+
303
  # Compile
304
  app = workflow.compile()
305
  return app
climateqa/engine/talk_to_data/drias_metadata.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "Frequency of rainy days index": {
3
+ "description": "Frequency_of_rainy_days_index table contains the frequency index of rainy days for each latitude longitude couple for each date in the past and the future.\nThe columns include:\n- `time`: Timestamp representing the date of the data.\n- `x`: Coordinate in the Lambert II projection for the location.\n- `y`: Coordinate in the Lambert II projection for the location.\n- `IFM40D`: Frequency index of rainy days.\n- `Lon`: Geographic longitude of the location.\n- `lat`: Geographic latitude of the location.",
4
+ "sql_query": "CREATE TABLE Frequency_of_rainy_days_index (\n time TIMESTAMP,\n x FLOAT,\n y FLOAT,\n IFM40D FLOAT,\n Lon FLOAT,\n lat FLOAT\n);"
5
+ },
6
+ "Remarkable daily precipitation total (Q99)": {
7
+ "description": "Remarkable_daily_precipitation_total_ total table contains the daily cumulative exceptional rainfall (Q99) for each latitude longitude couple for each date in the past and the future.\nThe columns include:\n- `time`: Timestamp representing the date of the data.\n- `x`: Coordinate in the Lambert II projection for the location.\n- `y`: Coordinate in the Lambert II projection for the location.\n- `LambertParisII`: Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- `RRq99`: Cumulative exceptional rainfall.\n- `lat`: Geographic latitude of the location.\n- `lon`: Geographic longitude of the location.",
8
+ "sql_query": "CREATE TABLE Remarkable_daily_precipitation_total_(Q99) (\n time TIMESTAMP,\n x FLOAT,\n y FLOAT,\n LambertParisII VARCHAR(255),\n RRq99 FLOAT,\n lat FLOAT,\n lon FLOAT\n);"
9
+ },
10
+ "Frequency of remarkable daily precipitation": {
11
+ "description": "The Frequency of remarkable daily precipitation table contains the frequency of daily exceptional rainfall in the past and the future.\nThe columns include:\n- `time`: Timestamp representing the date of the data.\n- `x`: Coordinate in the Lambert II projection for the location.\n- `y`: Coordinate in the Lambert II projection for the location.\n- `LambertParisII`: Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- `RRq99refD`: Frequency of exceptional rainfall.\n- `lat`: Geographic latitude of the location.\n- `lon`: Geographic longitude of the location.",
12
+ "sql_query": "CREATE TABLE Frequency_of_remarkable_daily_precipitation (\n time TIMESTAMP,\n x FLOAT,\n y FLOAT,\n LambertParisII VARCHAR(255),\n RRq99refD FLOAT,\n lat FLOAT,\n lon FLOAT\n);"
13
+ },
14
+ "Winter precipitation total": {
15
+ "description": "The Winter precipitation total table contains the cumulative winter precipitation in the past and the future.\nThe columns include:\n- `time`: Timestamp representing the date of the data.\n- `x`: Coordinate in the Lambert II projection for the location.\n- `y`: Coordinate in the Lambert II projection for the location.\n- `LambertParisII`: Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- `RR`: Cumulative winter precipitation.\n- `lat`: Geographic latitude of the location.\n- `lon`: Geographic longitude of the location.",
16
+ "sql_query": "CREATE TABLE Winter_precipitation_total (\n time TIMESTAMP,\n x FLOAT,\n y FLOAT,\n LambertParisII VARCHAR(255),\n RR FLOAT,\n lat FLOAT,\n lon FLOAT\n);"
17
+ },
18
+ "Summer precipitation total": {
19
+ "description": "The Summer precipitation total table contains the cumulative summer precipitation in the past and the future.\nThe columns include:\n- `time`: Timestamp representing the date of the data.\n- `x`: Coordinate in the Lambert II projection for the location.\n- `y`: Coordinate in the Lambert II projection for the location.\n- `LambertParisII`: Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- `RR`: Cumulative summer precipitation.\n- `lat`: Geographic latitude of the location.\n- `lon`: Geographic longitude of the location.",
20
+ "sql_query": "CREATE TABLE Summer_precipitation_total (\n time TIMESTAMP,\n x FLOAT,\n y FLOAT,\n LambertParisII VARCHAR(255),\n RR FLOAT,\n lat FLOAT,\n lon FLOAT\n);"
21
+ },
22
+ "Annual precipitation total": {
23
+ "description": "The Annual precipitation total table contains information on the cumulative annual precipitation in the past and the future.\nbased on Lambert Paris II projections.\nThe variables are as follows:\n- 'y' and 'x': Lambert Paris II coordinates for the location.\n- 'time': Timestamp indicating the observation period.\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- 'lat' and 'lon': Latitude and longitude of the location.\n- 'RR': Cumulative annual precipitation.",
24
+ "sql_query": "CREATE TABLE Annual_precipitation_total (\n y FLOAT,\n x FLOAT,\n time TIMESTAMP,\n LambertParisII VARCHAR(255),\n lat FLOAT,\n lon FLOAT,\n RR FLOAT\n);"
25
+ },
26
+ "Extreme precipitation intensity": {
27
+ "description": "The Extreme precipitation intensity table contains information on the intensity of extreme precipitation in the past and the future,\nwhich represents the maximum value of total annual precipitation.\nThe variables are as follows:\n- 'y' and 'x': Lambert Paris II coordinates for the location.\n- 'time': Timestamp indicating the observation period.\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- 'lat' and 'lon': Latitude and longitude of the location.\n- 'RX1d': Intensity of extreme precipitation (maximum annual total precipitation).",
28
+ "sql_query": "CREATE TABLE Extreme_precipitation_intensity (\n y FLOAT,\n x FLOAT,\n time TIMESTAMP,\n LambertParisII VARCHAR(255),\n lat FLOAT,\n lon FLOAT,\n RX1d FLOAT\n);"
29
+ },
30
+ "Drought index": {
31
+ "description": "The Drought index table contains information on the drought index based on observations over the past and the future.\nThe variables are as follows:\n- 'time': Timestamp indicating the observation period.\n- 'y' and 'x': Lambert Paris II coordinates for the location.\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- 'lat' and 'lon': Latitude and longitude of the location.\n- 'SWI04D': Drought index based on the analysis of precipitation and temperatures.",
32
+ "sql_query": "CREATE TABLE Drought_index (\n time TIMESTAMP,\n y FLOAT,\n x FLOAT,\n lat FLOAT,\n lon FLOAT,\n LambertParisII VARCHAR(255),\n SWI04D FLOAT\n);"
33
+ },
34
+ "Mean winter temperature": {
35
+ "description": "The Mean winter temperature table contains information on the average (mean) winter temperature in the past and the future.\nThe variables are as follows:\n- 'y' and 'x': Lambert Paris II coordinates for the location.\n- 'time': Timestamp indicating the observation period.\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- 'lat' and 'lon': Latitude and longitude of the location.\n- 'TMm': Average winter temperature.",
36
+ "sql_query": "CREATE TABLE Mean_winter_temperature (\n y FLOAT,\n x FLOAT,\n time TIMESTAMP,\n LambertParisII VARCHAR(255),\n lat FLOAT,\n lon FLOAT,\n TMm FLOAT\n);"
37
+ },
38
+ "Mean summer temperature": {
39
+ "description": "The Mean summer temperature table contains information on the average summer temperature in the past and the future.\nThe variables are as follows:\n- 'y' and 'x': Lambert Paris II coordinates for the location.\n- 'time': Timestamp indicating the observation period.\n- 'LambertParisII': Indicates that the x and y coordinates are in Lambert Paris II projection.\n- 'lat' and 'lon': Latitude and longitude of the location.\n- 'TMm': Average summer temperature.",
40
+ "sql_query": "CREATE TABLE Mean_summer_temperature (\n y FLOAT,\n x FLOAT,\n time TIMESTAMP,\n LambertParisII VARCHAR(255),\n lat FLOAT,\n lon FLOAT,\n TMm FLOAT\n);"
41
+ },
42
+ "Number of tropical nights": {
43
+ "description": "The Number of tropical nights table contains information on the average summer temperature in the past and the future.\nThe variables are as follows:\n- 'y' and 'x': Lambert Paris II coordinates for the location.\n- 'time': Timestamp indicating the observation period.\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- 'lat' and 'lon': Latitude and longitude of the location.\n- 'TMm': Average summer temperature.",
44
+ "sql_query": "CREATE TABLE Number_of_tropical_nights (\n y FLOAT,\n x FLOAT,\n time TIMESTAMP,\n LambertParisII VARCHAR(255),\n lat FLOAT,\n lon FLOAT,\n TR FLOAT\n);"
45
+ },
46
+ "Number of days with Tx above 30C": {
47
+ "description": "The Number of days with Tx above 30C table contains information on the number of days when the maximum temperature in the past and the future\nis greater than or equal to 30°C.\nThe variables are as follows:\n- 'y' and 'x': Lambert Paris II coordinates for the location.\n- 'time': Timestamp indicating the observation period.\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- 'lat' and 'lon': Latitude and longitude of the location.\n- 'TX30D': Number of days with Tx ≥ 30°C.",
48
+ "sql_query": "CREATE TABLE Number_of_days_with_Tx_above_30C (\n y FLOAT,\n x FLOAT,\n time TIMESTAMP,\n LambertParisII VARCHAR(255),\n lat FLOAT,\n lon FLOAT,\n TX30D FLOAT\n);"
49
+ },
50
+ "Number of days with Tx above 35C": {
51
+ "description": "The Number of days with Tx above 35C table contains information on the number of days when the maximum temperature in the past and the future\nis greater than or equal to 35°C.\nThe variables are as follows:\n- 'y' and 'x': Lambert Paris II coordinates for the location.\n- 'time': Timestamp indicating the observation period.\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- 'lat' and 'lon': Latitude and longitude of the location.\n- 'TX35D': Number of days with Tx ≥ 35°C.",
52
+ "sql_query": "CREATE TABLE Number_of_days_with_Tx_above_35C (\n y FLOAT,\n x FLOAT,\n time TIMESTAMP,\n LambertParisII VARCHAR(255),\n lat FLOAT,\n lon FLOAT,\n TX35D FLOAT\n);"
53
+ },
54
+ "Maximum summer temperature": {
55
+ "description": "The Maximum summer temperature table contains information on the maximum temperature in summer in the past and the future,\nwhich is the highest temperature recorded during the summer period.\nThe variables are as follows:\n- 'y' and 'x': Lambert Paris II coordinates for the location.\n- 'time': Timestamp indicating the observation period.\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\n- 'lat' and 'lon': Latitude and longitude of the location.\n- 'TXm': Maximum temperature recorded in summer.",
56
+ "sql_query": "CREATE TABLE Maximum_summer_temperature (\n y FLOAT,\n x FLOAT,\n time TIMESTAMP,\n LambertParisII VARCHAR(255),\n lat FLOAT,\n lon FLOAT,\n TXm FLOAT\n);"
57
+ }
58
+ }
climateqa/engine/talk_to_data/how_to_use_main.ipynb ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "## Import the function in main.py"
8
+ ]
9
+ },
10
+ {
11
+ "cell_type": "code",
12
+ "execution_count": 3,
13
+ "metadata": {},
14
+ "outputs": [
15
+ {
16
+ "name": "stdout",
17
+ "output_type": "stream",
18
+ "text": [
19
+ "The autoreload extension is already loaded. To reload it, use:\n",
20
+ " %reload_ext autoreload\n"
21
+ ]
22
+ }
23
+ ],
24
+ "source": [
25
+ "import sys\n",
26
+ "import os\n",
27
+ "sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))\n",
28
+ "\n",
29
+ "%load_ext autoreload\n",
30
+ "%autoreload 2\n",
31
+ "\n",
32
+ "from main import ask_vanna\n"
33
+ ]
34
+ },
35
+ {
36
+ "cell_type": "markdown",
37
+ "metadata": {},
38
+ "source": [
39
+ "## Create a human query"
40
+ ]
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "execution_count": 4,
45
+ "metadata": {},
46
+ "outputs": [],
47
+ "source": [
48
+ "query = \"what is the number of days where the temperature above 35 in 2050 in Marseille\"\n",
49
+ "# query = \"Compare the winter and summer precipitation in 2050 in Marseille\"\n",
50
+ "# query = \"What is the impact of climate in Bordeaux?\"\n",
51
+ "query = \"Quelle sera la température à Marseille sur les prochaines années ?\""
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "markdown",
56
+ "metadata": {},
57
+ "source": [
58
+ "## Call the function ask vanna, it gives an output of a the sql query and the dataframe of the result (tuple)"
59
+ ]
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "execution_count": 5,
64
+ "metadata": {},
65
+ "outputs": [
66
+ {
67
+ "name": "stdout",
68
+ "output_type": "stream",
69
+ "text": [
70
+ "SQL Prompt: [{'role': 'system', 'content': \"You are a SQLite expert. Please help to generate a SQL query to answer the question. Your response should ONLY be based on the given context and follow the response guidelines and format instructions. \\n===Tables \\n\\n CREATE TABLE Mean_winter_temperature (\\n y FLOAT,\\n x FLOAT,\\n year INT, \\n month INT, \\n day INT \\n,\\n LambertParisII VARCHAR(255),\\n lat FLOAT,\\n lon FLOAT,\\n TMm FLOAT, -- Température moyenne en hiver\\n );\\n \\n\\n\\n CREATE TABLE Mean_summer_temperature (\\n y FLOAT,\\n x FLOAT,\\n year INT, \\n month INT, \\n day INT \\n,\\n LambertParisII VARCHAR(255),\\n lat FLOAT,\\n lon FLOAT,\\n TMm FLOAT, -- Température moyenne en été\\n );\\n \\n\\n\\n===Additional Context \\n\\n\\n The Number of days with Tx above 35C table contains information on the number of days when the maximum temperature in the past and the future\\n is greater than or equal to 35°C.\\n The variables are as follows:\\n - 'y' and 'x': Lambert Paris II coordinates for the location.\\n - year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n - 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n - 'lat' and 'lon': Latitude and longitude of the location.\\n - 'TX35D': Number of days with Tx ≥ 35°C.\\n \\n\\n\\n The Number of days with Tx above 30C table contains information on the number of days when the maximum temperature in the past and the future\\n is greater than or equal to 30°C.\\n The variables are as follows:\\n - 'y' and 'x': Lambert Paris II coordinates for the location.\\n - year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n - 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n - 'lat' and 'lon': Latitude and longitude of the location.\\n - 'TX30D': Number of days with Tx ≥ 30°C.\\n \\n\\n===Response Guidelines \\n1. If the provided context is sufficient, please generate a valid SQL query without any explanations for the question. \\n2. If the provided context is almost sufficient but requires knowledge of a specific string in a particular column, please generate an intermediate SQL query to find the distinct strings in that column. Prepend the query with a comment saying intermediate_sql \\n3. If the provided context is insufficient, please explain why it can't be generated. \\n4. Please use the most relevant table(s). \\n5. If the question has been asked and answered before, please repeat the answer exactly as it was given before. \\n6. Ensure that the output SQL is SQLite-compliant and executable, and free of syntax errors. \\n\"}, {'role': 'user', 'content': 'Quelle sera la température à lat, long : (43.2961743, 5.3699525) sur les prochaines années ?'}]\n",
71
+ "Using model gpt-4o-mini for 828.0 tokens (approx)\n",
72
+ "LLM Response: ```sql\n",
73
+ "SELECT year, TMm \n",
74
+ "FROM Mean_winter_temperature \n",
75
+ "WHERE lat = 43.2961743 AND lon = 5.3699525\n",
76
+ "UNION ALL\n",
77
+ "SELECT year, TMm \n",
78
+ "FROM Mean_summer_temperature \n",
79
+ "WHERE lat = 43.2961743 AND lon = 5.3699525;\n",
80
+ "```\n",
81
+ "Extracted SQL: SELECT year, TMm \n",
82
+ "FROM Mean_winter_temperature \n",
83
+ "WHERE lat = 43.2961743 AND lon = 5.3699525\n",
84
+ "UNION ALL\n",
85
+ "SELECT year, TMm \n",
86
+ "FROM Mean_summer_temperature \n",
87
+ "WHERE lat = 43.2961743 AND lon = 5.3699525;\n",
88
+ "Using model gpt-4o-mini for 218.5 tokens (approx)\n",
89
+ "[(2031, 9.952474117647114), (2031, 9.952474117647114), (2032, 10.142322941176474), (2032, 10.142322941176474), (2033, 9.907942941176486), (2033, 9.907942941176486), (2034, 9.548873529411765), (2034, 9.548873529411765), (2035, 10.284758235294191), (2035, 10.284758235294191), (2036, 10.372100000000046), (2036, 10.372100000000046), (2037, 9.98571000000004), (2037, 9.98571000000004), (2038, 10.221372352941216), (2038, 10.221372352941216), (2039, 10.222609411764722), (2039, 10.222609411764722), (2040, 10.473662941176485), (2040, 10.473662941176485), (2041, 10.427640588235306), (2041, 10.427640588235306), (2042, 10.364736470588241), (2042, 10.364736470588241), (2043, 10.112910588235309), (2043, 10.112910588235309), (2044, 10.250792352941176), (2044, 10.250792352941176), (2045, 10.166119411764669), (2045, 10.166119411764669), (2046, 10.728997647058861), (2046, 10.728997647058861), (2047, 10.347248823529412), (2047, 10.347248823529412), (2048, 10.706604117647089), (2048, 10.706604117647089), (2049, 10.59243764705883), (2049, 10.59243764705883), (2050, 10.63225529411767), (2050, 10.63225529411767), (2031, 24.061035294117687), (2031, 24.061035294117687), (2032, 24.530692941176483), (2032, 24.530692941176483), (2033, 24.722234705882386), (2033, 24.722234705882386), (2034, 23.84629176470588), (2034, 23.84629176470588), (2035, 24.231422352941195), (2035, 24.231422352941195), (2036, 24.488941764705885), (2036, 24.488941764705885), (2037, 24.79424117647062), (2037, 24.79424117647062), (2038, 24.730553529411793), (2038, 24.730553529411793), (2039, 24.44979882352942), (2039, 24.44979882352942), (2040, 24.40726882352942), (2040, 24.40726882352942), (2041, 24.768547647058824), (2041, 24.768547647058824), (2042, 24.53479647058822), (2042, 24.53479647058822), (2043, 24.769181176470624), (2043, 24.769181176470624), (2044, 24.489877058823538), (2044, 24.489877058823538), (2045, 24.448076470588262), (2045, 24.448076470588262), (2046, 25.111282352941203), (2046, 25.111282352941203), (2047, 24.72313823529413), (2047, 24.72313823529413), (2048, 25.187577058823535), (2048, 25.187577058823535), (2049, 24.829653529411814), (2049, 24.829653529411814), (2050, 25.053394117647144), (2050, 25.053394117647144)]\n"
90
+ ]
91
+ },
92
+ {
93
+ "data": {
94
+ "text/plain": [
95
+ "('SELECT year, TMm \\nFROM Mean_winter_temperature \\nWHERE lat = 43.166954040527344 AND lon = 5.430534839630127\\nUNION ALL\\nSELECT year, TMm \\nFROM Mean_summer_temperature \\nWHERE lat = 43.166954040527344 AND lon = 5.430534839630127;',\n",
96
+ " year TMm\n",
97
+ " 0 2031 9.952474\n",
98
+ " 1 2031 9.952474\n",
99
+ " 2 2032 10.142323\n",
100
+ " 3 2032 10.142323\n",
101
+ " 4 2033 9.907943\n",
102
+ " .. ... ...\n",
103
+ " 75 2048 25.187577\n",
104
+ " 76 2049 24.829654\n",
105
+ " 77 2049 24.829654\n",
106
+ " 78 2050 25.053394\n",
107
+ " 79 2050 25.053394\n",
108
+ " \n",
109
+ " [80 rows x 2 columns])"
110
+ ]
111
+ },
112
+ "execution_count": 5,
113
+ "metadata": {},
114
+ "output_type": "execute_result"
115
+ }
116
+ ],
117
+ "source": [
118
+ "ask_vanna(query)"
119
+ ]
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "execution_count": null,
124
+ "metadata": {},
125
+ "outputs": [],
126
+ "source": []
127
+ }
128
+ ],
129
+ "metadata": {
130
+ "kernelspec": {
131
+ "display_name": "climateqa",
132
+ "language": "python",
133
+ "name": "python3"
134
+ },
135
+ "language_info": {
136
+ "codemirror_mode": {
137
+ "name": "ipython",
138
+ "version": 3
139
+ },
140
+ "file_extension": ".py",
141
+ "mimetype": "text/x-python",
142
+ "name": "python",
143
+ "nbconvert_exporter": "python",
144
+ "pygments_lexer": "ipython3",
145
+ "version": "3.11.9"
146
+ }
147
+ },
148
+ "nbformat": 4,
149
+ "nbformat_minor": 2
150
+ }
climateqa/engine/talk_to_data/main.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from climateqa.engine.talk_to_data.myVanna import MyVanna
2
+ from climateqa.engine.talk_to_data.utils import loc2coords, detect_location_with_openai, detectTable, nearestNeighbourSQL
3
+ import sqlite3
4
+ import os
5
+ import pandas as pd
6
+ from climateqa.engine.llm import get_llm
7
+ import ast
8
+
9
+ from dotenv import load_dotenv
10
+
11
+ load_dotenv()
12
+
13
+
14
+ OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
15
+ PC_API_KEY = os.getenv('VANNA_PINECONE_API_KEY')
16
+ INDEX_NAME = os.getenv('VANNA_INDEX_NAME')
17
+ VANNA_MODEL = os.getenv('VANNA_MODEL')
18
+
19
+
20
+ #Vanna object
21
+ vn = MyVanna(config = {"temperature": 0, "api_key": OPENAI_API_KEY, 'model': VANNA_MODEL, 'pc_api_key': PC_API_KEY, 'index_name': INDEX_NAME, "top_k" : 4})
22
+ db_vanna_path = os.path.join(os.path.dirname(__file__), "database/drias.db")
23
+ vn.connect_to_sqlite(db_vanna_path)
24
+
25
+ llm = get_llm(provider="openai")
26
+
27
+ # def ask_vanna(query):
28
+ # location = detect_location_with_openai(OPENAI_API_KEY, query)
29
+ # if location:
30
+ # coords = loc2coords(location)
31
+ # user_input = query.replace(location, f"lat, long : {coords}")
32
+ # answer = vn.ask(user_input, print_results=False, allow_llm_to_see_data=True)
33
+ # table = detectTable(answer[0])
34
+ # coords2 = nearestNeighbourSQL(db_vanna_path, coords, table[0])
35
+
36
+ # query = answer[0].replace(f"{coords[0]}", f"{coords2[0]}")
37
+ # sql_query = query.replace(f"{coords[1]}", f"{coords2[1]}")
38
+
39
+ # db = sqlite3.connect(db_vanna_path)
40
+ # result = db.cursor().execute(sql_query).fetchall()
41
+ # print(result)
42
+ # df = pd.DataFrame(result, columns=answer[1].columns)
43
+
44
+ # else:
45
+ # answer = vn.ask(query, visualize=True, print_results=False, allow_llm_to_see_data=True)
46
+ # sql_query = answer[0]
47
+ # df = answer[1]
48
+
49
+ # return (sql_query, df)
50
+ def replace_coordonates(coords, sql_query, coords_tables):
51
+ n = sql_query.count(str(coords[0]))
52
+ sql_query_new_coords = sql_query
53
+
54
+ for i in range(n):
55
+ sql_query_new_coords = sql_query_new_coords.replace(str(coords[0]), str(coords_tables[i][0]),1)
56
+ sql_query_new_coords = sql_query_new_coords.replace(str(coords[1]), str(coords_tables[i][1]),1)
57
+ return sql_query_new_coords
58
+
59
+ def ask_vanna(query):
60
+ location = detect_location_with_openai(OPENAI_API_KEY, query)
61
+ if location:
62
+
63
+ coords = loc2coords(location)
64
+ user_input = query.replace(location, f"lat, long : {coords}")
65
+ sql_query, result_dataframe, figure = vn.ask(user_input, print_results=False, allow_llm_to_see_data=True)
66
+ table = detectTable(sql_query)
67
+ coords_tables = [nearestNeighbourSQL(db_vanna_path, coords, table[i]) for i in range(len(table))]
68
+ sql_query_new_coords = replace_coordonates(coords, sql_query, coords_tables)
69
+ sql_with_table_names = llm.invoke(f"Make the following sql query display the source table in the rows {sql_query_new_coords}. Just answer the query. The answer should not include ```sql\n").content
70
+ print("execute sql query : ", sql_with_table_names)
71
+ db = sqlite3.connect(db_vanna_path)
72
+ result = db.cursor().execute(sql_query_new_coords).fetchall()
73
+ columns = llm.invoke(f"From the given sql query, list the columns that are being selected. The answer should only be a python list. Just answer the list. The SQL query : {sql_query_new_coords}").content
74
+ columns_list = ast.literal_eval(columns.strip("```python\n").strip())
75
+ print("column list : ",columns_list)
76
+ df = pd.DataFrame(result, columns=columns_list)
77
+
78
+ plotly_code = vn.generate_plotly_code(
79
+ question="query",
80
+ sql="sql_with_table_names",
81
+ df_metadata=f"Running df.dtypes gives:\n {df.dtypes}",
82
+ )
83
+
84
+ fig = vn.get_plotly_figure(plotly_code=plotly_code, df=df)
85
+
86
+ return df, fig
87
+ else :
88
+ empty_df = pd.DataFrame()
89
+ empty_fig = {}
90
+ return empty_df, empty_fig
climateqa/engine/talk_to_data/myVanna.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ from climateqa.engine.talk_to_data.vanna_class import MyCustomVectorDB
3
+ from vanna.openai import OpenAI_Chat
4
+ import os
5
+
6
+ load_dotenv()
7
+
8
+ OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
9
+
10
+ class MyVanna(MyCustomVectorDB, OpenAI_Chat):
11
+ def __init__(self, config=None):
12
+ MyCustomVectorDB.__init__(self, config=config)
13
+ OpenAI_Chat.__init__(self, config=config)
climateqa/engine/talk_to_data/pinecone_vanna_training.ipynb ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 37,
6
+ "metadata": {},
7
+ "outputs": [
8
+ {
9
+ "name": "stdout",
10
+ "output_type": "stream",
11
+ "text": [
12
+ "The autoreload extension is already loaded. To reload it, use:\n",
13
+ " %reload_ext autoreload\n",
14
+ "{'temperature': 0.2, 'api_key': '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', 'model': 'gpt-4o-mini', 'pc_api_key': 'pcsk_5pEfJ8_GqSCikBaVhK3V6wehh4YHCegspQeshyWVesKeqmqzcmfLgkQRpWaUVJvSyTcdG', 'index_name': 'cqa-vanna'}\n",
15
+ "Loading embeddings model: BAAI/bge-base-en-v1.5\n"
16
+ ]
17
+ }
18
+ ],
19
+ "source": [
20
+ "from vanna_class import MyCustomVectorDB\n",
21
+ "from vanna.openai import OpenAI_Chat\n",
22
+ "import os\n",
23
+ "from dotenv import load_dotenv\n",
24
+ "\n",
25
+ "%load_ext autoreload\n",
26
+ "%autoreload 2\n",
27
+ "\n",
28
+ "load_dotenv()\n",
29
+ "\n",
30
+ "OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')\n",
31
+ "OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')\n",
32
+ "PC_API_KEY = os.getenv('VANNA_PINECONE_API_KEY')\n",
33
+ "INDEX_NAME = os.getenv('VANNA_INDEX_NAME')\n",
34
+ "VANNA_MODEL = os.getenv('VANNA_MODEL')\n",
35
+ "\n",
36
+ "INDEX_NAME = \"cqa-vanna\"\n",
37
+ "PC_API_KEY = \"pcsk_5pEfJ8_GqSCikBaVhK3V6wehh4YHCegspQeshyWVesKeqmqzcmfLgkQRpWaUVJvSyTcdG\"\n",
38
+ "\n",
39
+ "class MyVanna(MyCustomVectorDB, OpenAI_Chat):\n",
40
+ " def __init__(self, config=None):\n",
41
+ " print(config)\n",
42
+ " MyCustomVectorDB.__init__(self, config=config)\n",
43
+ " OpenAI_Chat.__init__(self, config=config)\n",
44
+ "\n",
45
+ "vn = MyVanna(\n",
46
+ " config={\n",
47
+ " 'temperature': 0.2,\n",
48
+ " 'api_key': OPENAI_API_KEY,\n",
49
+ " 'model': 'gpt-4o-mini',\n",
50
+ " 'pc_api_key': PC_API_KEY,\n",
51
+ " 'index_name': INDEX_NAME\n",
52
+ " }\n",
53
+ ")"
54
+ ]
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "execution_count": 49,
59
+ "metadata": {},
60
+ "outputs": [],
61
+ "source": [
62
+ "import json\n",
63
+ "\n",
64
+ "with open('drias_metadata.json', 'r') as file:\n",
65
+ " tables_info = json.load(file)\n"
66
+ ]
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "execution_count": 50,
71
+ "metadata": {},
72
+ "outputs": [],
73
+ "source": [
74
+ "def convert(tables_info):\n",
75
+ " text = \"\"\"- year: Year of the observation.\\n\n",
76
+ " - month : Month of the observation.\\n\n",
77
+ " - day: Day of the observation.\\n\"\"\"\n",
78
+ " for table_name in tables_info:\n",
79
+ " tables_info[table_name]['description'] = tables_info[table_name]['description'].replace(\"- 'time': Timestamp indicating the observation period.\", text)\n",
80
+ " tables_info[table_name]['description'] = tables_info[table_name]['description'].replace(\"- `time`: Timestamp representing the date of the data.\", text)\n",
81
+ " tables_info[table_name]['sql_query'] = tables_info[table_name]['sql_query'].replace(\"time TIMESTAMP\", \"year INT, \\n month INT, \\n day INT \\n\")\n",
82
+ " \n",
83
+ " return tables_info"
84
+ ]
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "execution_count": 51,
89
+ "metadata": {},
90
+ "outputs": [
91
+ {
92
+ "data": {
93
+ "text/plain": [
94
+ "{'Frequency of rainy days index': {'description': 'The Frequency of rainy days index table contains the frequency index of rainy days for each latitude longitude couple for each date in the past and the future.\\nThe columns include:\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- `x`: Coordinate in the Lambert II projection for the location.\\n- `y`: Coordinate in the Lambert II projection for the location.\\n- `IFM40D`: Frequency index of rainy days.\\n- `Lon`: Geographic longitude of the location.\\n- `lat`: Geographic latitude of the location.',\n",
95
+ " 'sql_query': 'CREATE TABLE Frequency_of_rainy_days_index (\\n year INT, \\n month INT, \\n day INT \\n,\\n x FLOAT,\\n y FLOAT,\\n IFM40D FLOAT,\\n Lon FLOAT,\\n lat FLOAT\\n);'},\n",
96
+ " 'Remarkable daily precipitation total (Q99)': {'description': 'The Remarkable daily precipitation total table contains the daily cumulative exceptional rainfall (Q99) for each latitude longitude couple for each date in the past and the future.\\nThe columns include:\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- `x`: Coordinate in the Lambert II projection for the location.\\n- `y`: Coordinate in the Lambert II projection for the location.\\n- `LambertParisII`: Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- `RRq99`: Cumulative exceptional rainfall.\\n- `lat`: Geographic latitude of the location.\\n- `lon`: Geographic longitude of the location.',\n",
97
+ " 'sql_query': 'CREATE TABLE Remarkable_daily_precipitation_total_(Q99) (\\n year INT, \\n month INT, \\n day INT \\n,\\n x FLOAT,\\n y FLOAT,\\n LambertParisII VARCHAR(255),\\n RRq99 FLOAT,\\n lat FLOAT,\\n lon FLOAT\\n);'},\n",
98
+ " 'Frequency of remarkable daily precipitation': {'description': 'The Frequency of remarkable daily precipitation table contains the frequency of daily exceptional rainfall in the past and the future.\\nThe columns include:\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- `x`: Coordinate in the Lambert II projection for the location.\\n- `y`: Coordinate in the Lambert II projection for the location.\\n- `LambertParisII`: Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- `RRq99refD`: Frequency of exceptional rainfall.\\n- `lat`: Geographic latitude of the location.\\n- `lon`: Geographic longitude of the location.',\n",
99
+ " 'sql_query': 'CREATE TABLE Frequency_of_remarkable_daily_precipitation (\\n year INT, \\n month INT, \\n day INT \\n,\\n x FLOAT,\\n y FLOAT,\\n LambertParisII VARCHAR(255),\\n RRq99refD FLOAT,\\n lat FLOAT,\\n lon FLOAT\\n);'},\n",
100
+ " 'Winter precipitation total': {'description': 'The Winter precipitation total table contains the cumulative winter precipitation in the past and the future.\\nThe columns include:\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- `x`: Coordinate in the Lambert II projection for the location.\\n- `y`: Coordinate in the Lambert II projection for the location.\\n- `LambertParisII`: Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- `RR`: Cumulative winter precipitation.\\n- `lat`: Geographic latitude of the location.\\n- `lon`: Geographic longitude of the location.',\n",
101
+ " 'sql_query': 'CREATE TABLE Winter_precipitation_total (\\n year INT, \\n month INT, \\n day INT \\n,\\n x FLOAT,\\n y FLOAT,\\n LambertParisII VARCHAR(255),\\n RR FLOAT,\\n lat FLOAT,\\n lon FLOAT\\n);'},\n",
102
+ " 'Summer precipitation total': {'description': 'The Summer precipitation total table contains the cumulative summer precipitation in the past and the future.\\nThe columns include:\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- `x`: Coordinate in the Lambert II projection for the location.\\n- `y`: Coordinate in the Lambert II projection for the location.\\n- `LambertParisII`: Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- `RR`: Cumulative summer precipitation.\\n- `lat`: Geographic latitude of the location.\\n- `lon`: Geographic longitude of the location.',\n",
103
+ " 'sql_query': 'CREATE TABLE Summer_precipitation_total (\\n year INT, \\n month INT, \\n day INT \\n,\\n x FLOAT,\\n y FLOAT,\\n LambertParisII VARCHAR(255),\\n RR FLOAT,\\n lat FLOAT,\\n lon FLOAT\\n);'},\n",
104
+ " 'Annual precipitation total': {'description': \"The Annual precipitation total table contains information on the cumulative annual precipitation in the past and the future.\\nbased on Lambert Paris II projections.\\nThe variables are as follows:\\n- 'y' and 'x': Lambert Paris II coordinates for the location.\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- 'lat' and 'lon': Latitude and longitude of the location.\\n- 'RR': Cumulative annual precipitation.\",\n",
105
+ " 'sql_query': 'CREATE TABLE Annual_precipitation_total (\\n y FLOAT,\\n x FLOAT,\\n year INT, \\n month INT, \\n day INT \\n,\\n LambertParisII VARCHAR(255),\\n lat FLOAT,\\n lon FLOAT,\\n RR FLOAT\\n);'},\n",
106
+ " 'Extreme precipitation intensity': {'description': \"The Extreme precipitation intensity table contains information on the intensity of extreme precipitation in the past and the future,\\nwhich represents the maximum value of total annual precipitation.\\nThe variables are as follows:\\n- 'y' and 'x': Lambert Paris II coordinates for the location.\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- 'lat' and 'lon': Latitude and longitude of the location.\\n- 'RX1d': Intensity of extreme precipitation (maximum annual total precipitation).\",\n",
107
+ " 'sql_query': 'CREATE TABLE Extreme_precipitation_intensity (\\n y FLOAT,\\n x FLOAT,\\n year INT, \\n month INT, \\n day INT \\n,\\n LambertParisII VARCHAR(255),\\n lat FLOAT,\\n lon FLOAT,\\n RX1d FLOAT\\n);'},\n",
108
+ " 'Drought index': {'description': \"The Drought index table contains information on the drought index based on observations over the past and the future.\\nThe variables are as follows:\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- 'y' and 'x': Lambert Paris II coordinates for the location.\\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- 'lat' and 'lon': Latitude and longitude of the location.\\n- 'SWI04D': Drought index based on the analysis of precipitation and temperatures.\",\n",
109
+ " 'sql_query': 'CREATE TABLE Drought_index (\\n year INT, \\n month INT, \\n day INT \\n,\\n y FLOAT,\\n x FLOAT,\\n lat FLOAT,\\n lon FLOAT,\\n LambertParisII VARCHAR(255),\\n SWI04D FLOAT\\n);'},\n",
110
+ " 'Mean winter temperature': {'description': \"The Mean winter temperature table contains information on the average (mean) winter temperature in the past and the future.\\nThe variables are as follows:\\n- 'y' and 'x': Lambert Paris II coordinates for the location.\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- 'lat' and 'lon': Latitude and longitude of the location.\\n- 'TMm': Average winter temperature.\",\n",
111
+ " 'sql_query': 'CREATE TABLE Mean_winter_temperature (\\n y FLOAT,\\n x FLOAT,\\n year INT, \\n month INT, \\n day INT \\n,\\n LambertParisII VARCHAR(255),\\n lat FLOAT,\\n lon FLOAT,\\n TMm FLOAT\\n);'},\n",
112
+ " 'Mean summer temperature': {'description': \"The Mean summer temperature table contains information on the average summer temperature in the past and the future.\\nThe variables are as follows:\\n- 'y' and 'x': Lambert Paris II coordinates for the location.\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- 'LambertParisII': Indicates that the x and y coordinates are in Lambert Paris II projection.\\n- 'lat' and 'lon': Latitude and longitude of the location.\\n- 'TMm': Average summer temperature.\",\n",
113
+ " 'sql_query': 'CREATE TABLE Mean_summer_temperature (\\n y FLOAT,\\n x FLOAT,\\n year INT, \\n month INT, \\n day INT \\n,\\n LambertParisII VARCHAR(255),\\n lat FLOAT,\\n lon FLOAT,\\n TMm FLOAT\\n);'},\n",
114
+ " 'Number of tropical nights': {'description': \"The Number of tropical nights table contains information on the average summer temperature in the past and the future.\\nThe variables are as follows:\\n- 'y' and 'x': Lambert Paris II coordinates for the location.\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- 'lat' and 'lon': Latitude and longitude of the location.\\n- 'TMm': Average summer temperature.\",\n",
115
+ " 'sql_query': 'CREATE TABLE Number_of_tropical_nights (\\n y FLOAT,\\n x FLOAT,\\n year INT, \\n month INT, \\n day INT \\n,\\n LambertParisII VARCHAR(255),\\n lat FLOAT,\\n lon FLOAT,\\n TR FLOAT\\n);'},\n",
116
+ " 'Number of days with Tx above 30C': {'description': \"The Number of days with Tx above 30C table contains information on the number of days when the maximum temperature in the past and the future\\nis greater than or equal to 30°C.\\nThe variables are as follows:\\n- 'y' and 'x': Lambert Paris II coordinates for the location.\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- 'lat' and 'lon': Latitude and longitude of the location.\\n- 'TX30D': Number of days with Tx ≥ 30°C.\",\n",
117
+ " 'sql_query': 'CREATE TABLE Number_of_days_with_Tx_above_30C (\\n y FLOAT,\\n x FLOAT,\\n year INT, \\n month INT, \\n day INT \\n,\\n LambertParisII VARCHAR(255),\\n lat FLOAT,\\n lon FLOAT,\\n TX30D FLOAT\\n);'},\n",
118
+ " 'Number of days with Tx above 35C': {'description': \"The Number of days with Tx above 35C table contains information on the number of days when the maximum temperature in the past and the future\\nis greater than or equal to 35°C.\\nThe variables are as follows:\\n- 'y' and 'x': Lambert Paris II coordinates for the location.\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- 'lat' and 'lon': Latitude and longitude of the location.\\n- 'TX35D': Number of days with Tx ≥ 35°C.\",\n",
119
+ " 'sql_query': 'CREATE TABLE Number_of_days_with_Tx_above_35C (\\n y FLOAT,\\n x FLOAT,\\n year INT, \\n month INT, \\n day INT \\n,\\n LambertParisII VARCHAR(255),\\n lat FLOAT,\\n lon FLOAT,\\n TX35D FLOAT\\n);'},\n",
120
+ " 'Maximum summer temperature': {'description': \"The Maximum summer temperature table contains information on the maximum temperature in summer in the past and the future,\\nwhich is the highest temperature recorded during the summer period.\\nThe variables are as follows:\\n- 'y' and 'x': Lambert Paris II coordinates for the location.\\n- year: Year of the observation.\\n\\n - month : Month of the observation.\\n\\n - day: Day of the observation.\\n\\n- 'LambertParisII': Indicates that the x, y coordinates are in the Lambert Paris II projection.\\n- 'lat' and 'lon': Latitude and longitude of the location.\\n- 'TXm': Maximum temperature recorded in summer.\",\n",
121
+ " 'sql_query': 'CREATE TABLE Maximum_summer_temperature (\\n y FLOAT,\\n x FLOAT,\\n year INT, \\n month INT, \\n day INT \\n,\\n LambertParisII VARCHAR(255),\\n lat FLOAT,\\n lon FLOAT,\\n TXm FLOAT\\n);'}}"
122
+ ]
123
+ },
124
+ "execution_count": 51,
125
+ "metadata": {},
126
+ "output_type": "execute_result"
127
+ }
128
+ ],
129
+ "source": [
130
+ "new_tables_info = convert(tables_info)\n",
131
+ "new_tables_info\n"
132
+ ]
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "execution_count": 52,
137
+ "metadata": {},
138
+ "outputs": [
139
+ {
140
+ "name": "stdout",
141
+ "output_type": "stream",
142
+ "text": [
143
+ "Adding ddl: CREATE TABLE Frequency_of_rainy_days_index (\n",
144
+ " year INT, \n",
145
+ " month INT, \n",
146
+ " day INT \n",
147
+ ",\n",
148
+ " x FLOAT,\n",
149
+ " y FLOAT,\n",
150
+ " IFM40D FLOAT,\n",
151
+ " Lon FLOAT,\n",
152
+ " lat FLOAT\n",
153
+ ");\n"
154
+ ]
155
+ },
156
+ {
157
+ "name": "stdout",
158
+ "output_type": "stream",
159
+ "text": [
160
+ "Adding documentation....\n",
161
+ "Adding ddl: CREATE TABLE Remarkable_daily_precipitation_total_(Q99) (\n",
162
+ " year INT, \n",
163
+ " month INT, \n",
164
+ " day INT \n",
165
+ ",\n",
166
+ " x FLOAT,\n",
167
+ " y FLOAT,\n",
168
+ " LambertParisII VARCHAR(255),\n",
169
+ " RRq99 FLOAT,\n",
170
+ " lat FLOAT,\n",
171
+ " lon FLOAT\n",
172
+ ");\n",
173
+ "Adding documentation....\n",
174
+ "Adding ddl: CREATE TABLE Frequency_of_remarkable_daily_precipitation (\n",
175
+ " year INT, \n",
176
+ " month INT, \n",
177
+ " day INT \n",
178
+ ",\n",
179
+ " x FLOAT,\n",
180
+ " y FLOAT,\n",
181
+ " LambertParisII VARCHAR(255),\n",
182
+ " RRq99refD FLOAT,\n",
183
+ " lat FLOAT,\n",
184
+ " lon FLOAT\n",
185
+ ");\n",
186
+ "Adding documentation....\n",
187
+ "Adding ddl: CREATE TABLE Winter_precipitation_total (\n",
188
+ " year INT, \n",
189
+ " month INT, \n",
190
+ " day INT \n",
191
+ ",\n",
192
+ " x FLOAT,\n",
193
+ " y FLOAT,\n",
194
+ " LambertParisII VARCHAR(255),\n",
195
+ " RR FLOAT,\n",
196
+ " lat FLOAT,\n",
197
+ " lon FLOAT\n",
198
+ ");\n",
199
+ "Adding documentation....\n",
200
+ "Adding ddl: CREATE TABLE Summer_precipitation_total (\n",
201
+ " year INT, \n",
202
+ " month INT, \n",
203
+ " day INT \n",
204
+ ",\n",
205
+ " x FLOAT,\n",
206
+ " y FLOAT,\n",
207
+ " LambertParisII VARCHAR(255),\n",
208
+ " RR FLOAT,\n",
209
+ " lat FLOAT,\n",
210
+ " lon FLOAT\n",
211
+ ");\n",
212
+ "Adding documentation....\n",
213
+ "Adding ddl: CREATE TABLE Annual_precipitation_total (\n",
214
+ " y FLOAT,\n",
215
+ " x FLOAT,\n",
216
+ " year INT, \n",
217
+ " month INT, \n",
218
+ " day INT \n",
219
+ ",\n",
220
+ " LambertParisII VARCHAR(255),\n",
221
+ " lat FLOAT,\n",
222
+ " lon FLOAT,\n",
223
+ " RR FLOAT\n",
224
+ ");\n",
225
+ "Adding documentation....\n",
226
+ "Adding ddl: CREATE TABLE Extreme_precipitation_intensity (\n",
227
+ " y FLOAT,\n",
228
+ " x FLOAT,\n",
229
+ " year INT, \n",
230
+ " month INT, \n",
231
+ " day INT \n",
232
+ ",\n",
233
+ " LambertParisII VARCHAR(255),\n",
234
+ " lat FLOAT,\n",
235
+ " lon FLOAT,\n",
236
+ " RX1d FLOAT\n",
237
+ ");\n",
238
+ "Adding documentation....\n",
239
+ "Adding ddl: CREATE TABLE Drought_index (\n",
240
+ " year INT, \n",
241
+ " month INT, \n",
242
+ " day INT \n",
243
+ ",\n",
244
+ " y FLOAT,\n",
245
+ " x FLOAT,\n",
246
+ " lat FLOAT,\n",
247
+ " lon FLOAT,\n",
248
+ " LambertParisII VARCHAR(255),\n",
249
+ " SWI04D FLOAT\n",
250
+ ");\n",
251
+ "Adding documentation....\n",
252
+ "Adding ddl: CREATE TABLE Mean_winter_temperature (\n",
253
+ " y FLOAT,\n",
254
+ " x FLOAT,\n",
255
+ " year INT, \n",
256
+ " month INT, \n",
257
+ " day INT \n",
258
+ ",\n",
259
+ " LambertParisII VARCHAR(255),\n",
260
+ " lat FLOAT,\n",
261
+ " lon FLOAT,\n",
262
+ " TMm FLOAT\n",
263
+ ");\n",
264
+ "Adding documentation....\n",
265
+ "Adding ddl: CREATE TABLE Mean_summer_temperature (\n",
266
+ " y FLOAT,\n",
267
+ " x FLOAT,\n",
268
+ " year INT, \n",
269
+ " month INT, \n",
270
+ " day INT \n",
271
+ ",\n",
272
+ " LambertParisII VARCHAR(255),\n",
273
+ " lat FLOAT,\n",
274
+ " lon FLOAT,\n",
275
+ " TMm FLOAT\n",
276
+ ");\n",
277
+ "Adding documentation....\n",
278
+ "Adding ddl: CREATE TABLE Number_of_tropical_nights (\n",
279
+ " y FLOAT,\n",
280
+ " x FLOAT,\n",
281
+ " year INT, \n",
282
+ " month INT, \n",
283
+ " day INT \n",
284
+ ",\n",
285
+ " LambertParisII VARCHAR(255),\n",
286
+ " lat FLOAT,\n",
287
+ " lon FLOAT,\n",
288
+ " TR FLOAT\n",
289
+ ");\n",
290
+ "Adding documentation....\n",
291
+ "Adding ddl: CREATE TABLE Number_of_days_with_Tx_above_30C (\n",
292
+ " y FLOAT,\n",
293
+ " x FLOAT,\n",
294
+ " year INT, \n",
295
+ " month INT, \n",
296
+ " day INT \n",
297
+ ",\n",
298
+ " LambertParisII VARCHAR(255),\n",
299
+ " lat FLOAT,\n",
300
+ " lon FLOAT,\n",
301
+ " TX30D FLOAT\n",
302
+ ");\n",
303
+ "Adding documentation....\n",
304
+ "Adding ddl: CREATE TABLE Number_of_days_with_Tx_above_35C (\n",
305
+ " y FLOAT,\n",
306
+ " x FLOAT,\n",
307
+ " year INT, \n",
308
+ " month INT, \n",
309
+ " day INT \n",
310
+ ",\n",
311
+ " LambertParisII VARCHAR(255),\n",
312
+ " lat FLOAT,\n",
313
+ " lon FLOAT,\n",
314
+ " TX35D FLOAT\n",
315
+ ");\n",
316
+ "Adding documentation....\n",
317
+ "Adding ddl: CREATE TABLE Maximum_summer_temperature (\n",
318
+ " y FLOAT,\n",
319
+ " x FLOAT,\n",
320
+ " year INT, \n",
321
+ " month INT, \n",
322
+ " day INT \n",
323
+ ",\n",
324
+ " LambertParisII VARCHAR(255),\n",
325
+ " lat FLOAT,\n",
326
+ " lon FLOAT,\n",
327
+ " TXm FLOAT\n",
328
+ ");\n",
329
+ "Adding documentation....\n"
330
+ ]
331
+ }
332
+ ],
333
+ "source": [
334
+ "for table in new_tables_info:\n",
335
+ " vn.train(ddl = new_tables_info[table]['sql_query'])\n",
336
+ " vn.train(documentation = new_tables_info[table]['description'])"
337
+ ]
338
+ },
339
+ {
340
+ "cell_type": "markdown",
341
+ "metadata": {},
342
+ "source": [
343
+ "# Requests"
344
+ ]
345
+ },
346
+ {
347
+ "cell_type": "code",
348
+ "execution_count": null,
349
+ "metadata": {},
350
+ "outputs": [],
351
+ "source": []
352
+ },
353
+ {
354
+ "cell_type": "markdown",
355
+ "metadata": {},
356
+ "source": [
357
+ "# examples"
358
+ ]
359
+ },
360
+ {
361
+ "cell_type": "code",
362
+ "execution_count": 56,
363
+ "metadata": {},
364
+ "outputs": [
365
+ {
366
+ "name": "stdout",
367
+ "output_type": "stream",
368
+ "text": [
369
+ "Loading embeddings model: BAAI/bge-base-en-v1.5\n"
370
+ ]
371
+ }
372
+ ],
373
+ "source": [
374
+ "question_sql = [\n",
375
+ " # ['How will the precipitations change in the coming years', \n",
376
+ " # 'SELECT * FROM Annual_precipitation_total WHERE year > 2024;'],\n",
377
+ " # ['What is the number of days where the temperature above 35 in year 2050 in (lat, lon) = (48.82337188720703, 2.390951633453369)', \n",
378
+ " # 'SELECT TX35D FROM Number_of_days_with_Tx_above_35C WHERE year = 2050 AND lat = 48.82337188720703 AND lon = 2.390951633453369;'],\n",
379
+ " # ['How will change the mean winter temperature in the coming years in lat = 43.2961743 lon = 5.3699525', \n",
380
+ " # 'SELECT * FROM Mean_winter_temperature WHERE year > 2023 AND lat = 43.2961743 AND lon = 5.3699525'],\n",
381
+ " # ['How will change the mean summer temperature in the coming years in lat = 43.2961743, lon = 5.3699525', \n",
382
+ " # 'SELECT * FROM Mean_summer_temperature WHERE year > 2023 AND lat = 43.2961743 AND lon = 5.3699525'],\n",
383
+ " # ['How will change the temperature in the coming years', \n",
384
+ " # 'SELECT * FROM Mean_summer_temperature JOIN Mean_winter_temperature WHERE year > 2024']\n",
385
+ " [\"Quelle sera la température à lat, long : (43.2961743, 5.3699525) sur les prochaines années ?\",\n",
386
+ " 'SELECT Mean_winter_temperature AS table_name, lat, lon, year, TMm \\nFROM Mean_winter_temperature \\nWHERE lat = 43.2961743 AND lon = 5.3699525\\nUNION ALL\\nSELECT \"Mean_summer_temperature\" AS table_name, lat, lon, year, TMm \\nFROM Mean_summer_temperature \\nWHERE lat = 43.2961743 AND lon = 5.3699525;']\n",
387
+ "]"
388
+ ]
389
+ },
390
+ {
391
+ "cell_type": "code",
392
+ "execution_count": 58,
393
+ "metadata": {},
394
+ "outputs": [
395
+ {
396
+ "name": "stdout",
397
+ "output_type": "stream",
398
+ "text": [
399
+ "de6738cb3a67eaec29a04119ad160b27acd64f2d87cf83782c5b2bdc84be445b_sql\n"
400
+ ]
401
+ }
402
+ ],
403
+ "source": [
404
+ "for question in question_sql:\n",
405
+ " print(vn.train(question = question[0], sql = question[1]))"
406
+ ]
407
+ },
408
+ {
409
+ "cell_type": "markdown",
410
+ "metadata": {},
411
+ "source": [
412
+ "# Delete"
413
+ ]
414
+ },
415
+ {
416
+ "cell_type": "code",
417
+ "execution_count": 31,
418
+ "metadata": {},
419
+ "outputs": [
420
+ {
421
+ "data": {
422
+ "text/plain": [
423
+ "'cqa-vanna'"
424
+ ]
425
+ },
426
+ "execution_count": 31,
427
+ "metadata": {},
428
+ "output_type": "execute_result"
429
+ }
430
+ ],
431
+ "source": [
432
+ "INDEX_NAME"
433
+ ]
434
+ },
435
+ {
436
+ "cell_type": "code",
437
+ "execution_count": 36,
438
+ "metadata": {},
439
+ "outputs": [
440
+ {
441
+ "data": {
442
+ "text/plain": []
443
+ },
444
+ "execution_count": 36,
445
+ "metadata": {},
446
+ "output_type": "execute_result"
447
+ }
448
+ ],
449
+ "source": [
450
+ "from pinecone.grpc import PineconeGRPC as Pinecone\n",
451
+ "\n",
452
+ "pc = Pinecone(api_key=PC_API_KEY)\n",
453
+ "\n",
454
+ "# To get the unique host for an index, \n",
455
+ "# see https://docs.pinecone.io/guides/data/target-an-index\n",
456
+ "index = pc.Index(INDEX_NAME)\n",
457
+ "# index\n",
458
+ "index.delete(delete_all=True, namespace='ddl')\n",
459
+ "index.delete(delete_all=True, namespace='documentation')\n"
460
+ ]
461
+ },
462
+ {
463
+ "cell_type": "markdown",
464
+ "metadata": {},
465
+ "source": [
466
+ "# OLD"
467
+ ]
468
+ },
469
+ {
470
+ "cell_type": "code",
471
+ "execution_count": 32,
472
+ "metadata": {},
473
+ "outputs": [],
474
+ "source": [
475
+ "import vanna\n",
476
+ "from vanna.remote import VannaDefault"
477
+ ]
478
+ },
479
+ {
480
+ "cell_type": "code",
481
+ "execution_count": 33,
482
+ "metadata": {},
483
+ "outputs": [],
484
+ "source": [
485
+ "# PC_API_KEY = os.getenv('VANNA_PINECONE_API_KEY')\n"
486
+ ]
487
+ },
488
+ {
489
+ "cell_type": "code",
490
+ "execution_count": 34,
491
+ "metadata": {},
492
+ "outputs": [
493
+ {
494
+ "data": {
495
+ "text/plain": [
496
+ "[\n",
497
+ " {\n",
498
+ " \"name\": \"cqa-vanna\",\n",
499
+ " \"dimension\": 768,\n",
500
+ " \"metric\": \"cosine\",\n",
501
+ " \"host\": \"cqa-vanna-9xlylwt.svc.aped-4627-b74a.pinecone.io\",\n",
502
+ " \"spec\": {\n",
503
+ " \"serverless\": {\n",
504
+ " \"cloud\": \"aws\",\n",
505
+ " \"region\": \"us-east-1\"\n",
506
+ " }\n",
507
+ " },\n",
508
+ " \"status\": {\n",
509
+ " \"ready\": true,\n",
510
+ " \"state\": \"Ready\"\n",
511
+ " },\n",
512
+ " \"deletion_protection\": \"disabled\"\n",
513
+ " },\n",
514
+ " {\n",
515
+ " \"name\": \"unepqa\",\n",
516
+ " \"dimension\": 768,\n",
517
+ " \"metric\": \"cosine\",\n",
518
+ " \"host\": \"unepqa-9xlylwt.svc.aped-4627-b74a.pinecone.io\",\n",
519
+ " \"spec\": {\n",
520
+ " \"serverless\": {\n",
521
+ " \"cloud\": \"aws\",\n",
522
+ " \"region\": \"us-east-1\"\n",
523
+ " }\n",
524
+ " },\n",
525
+ " \"status\": {\n",
526
+ " \"ready\": true,\n",
527
+ " \"state\": \"Ready\"\n",
528
+ " },\n",
529
+ " \"deletion_protection\": \"disabled\"\n",
530
+ " }\n",
531
+ "]"
532
+ ]
533
+ },
534
+ "execution_count": 34,
535
+ "metadata": {},
536
+ "output_type": "execute_result"
537
+ }
538
+ ],
539
+ "source": [
540
+ "from pinecone.grpc import PineconeGRPC as Pinecone\n",
541
+ "\n",
542
+ "pc = Pinecone(api_key=PC_API_KEY)\n",
543
+ "pc.list_indexes()"
544
+ ]
545
+ },
546
+ {
547
+ "cell_type": "code",
548
+ "execution_count": 35,
549
+ "metadata": {},
550
+ "outputs": [
551
+ {
552
+ "data": {
553
+ "text/plain": [
554
+ "{'dimension': 768,\n",
555
+ " 'index_fullness': 0.0,\n",
556
+ " 'namespaces': {'ddl': {'vector_count': 14},\n",
557
+ " 'documentation': {'vector_count': 14}},\n",
558
+ " 'total_vector_count': 28}"
559
+ ]
560
+ },
561
+ "execution_count": 35,
562
+ "metadata": {},
563
+ "output_type": "execute_result"
564
+ }
565
+ ],
566
+ "source": [
567
+ "pc.Index(\"cqa-vanna\").describe_index_stats()"
568
+ ]
569
+ }
570
+ ],
571
+ "metadata": {
572
+ "kernelspec": {
573
+ "display_name": "climateqa",
574
+ "language": "python",
575
+ "name": "python3"
576
+ },
577
+ "language_info": {
578
+ "codemirror_mode": {
579
+ "name": "ipython",
580
+ "version": 3
581
+ },
582
+ "file_extension": ".py",
583
+ "mimetype": "text/x-python",
584
+ "name": "python",
585
+ "nbconvert_exporter": "python",
586
+ "pygments_lexer": "ipython3",
587
+ "version": "3.11.9"
588
+ }
589
+ },
590
+ "nbformat": 4,
591
+ "nbformat_minor": 2
592
+ }
climateqa/engine/talk_to_data/step_by_step_vanna.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
climateqa/engine/talk_to_data/utils.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import openai
3
+ import pandas as pd
4
+ from geopy.geocoders import Nominatim
5
+ import sqlite3
6
+
7
+
8
+ def detect_location_with_openai(api_key, sentence):
9
+ """
10
+ Detects locations in a sentence using OpenAI's API.
11
+ """
12
+ openai.api_key = api_key
13
+
14
+ prompt = f"""
15
+ Extract all locations (cities, countries, states, or geographical areas) mentioned in the following sentence.
16
+ Return the result as a Python list. If no locations are mentioned, return an empty list.
17
+
18
+ Sentence: "{sentence}"
19
+ """
20
+
21
+ response = openai.chat.completions.create(
22
+ model="gpt-4o-mini",
23
+ messages=[
24
+ {"role": "system", "content": "You are a helpful assistant skilled in identifying locations in text."},
25
+ {"role": "user", "content": prompt}
26
+ ],
27
+ max_tokens=100,
28
+ temperature=0
29
+ )
30
+
31
+ return response.choices[0].message.content.split("\n")[1][2:-2]
32
+
33
+
34
+ def detectTable(sql_query):
35
+ pattern = r'(?i)\bFROM\s+((?:`[^`]+`|"[^"]+"|\'[^\']+\'|\w+)(?:\.(?:`[^`]+`|"[^"]+"|\'[^\']+\'|\w+))*)'
36
+ matches = re.findall(pattern, sql_query)
37
+ return matches
38
+
39
+
40
+
41
+ def loc2coords(location : str):
42
+ geolocator = Nominatim(user_agent="city_to_latlong")
43
+ location = geolocator.geocode(location)
44
+ return (location.latitude, location.longitude)
45
+
46
+
47
+ def coords2loc(coords : tuple):
48
+ geolocator = Nominatim(user_agent="coords_to_city")
49
+ try:
50
+ location = geolocator.reverse(coords)
51
+ return location.address
52
+ except Exception as e:
53
+ print(f"Error: {e}")
54
+ return "Unknown Location"
55
+
56
+
57
+ def nearestNeighbourSQL(db: str, location: tuple, table : str):
58
+ conn = sqlite3.connect(db)
59
+ long = round(location[1], 3)
60
+ lat = round(location[0], 3)
61
+ cursor = conn.cursor()
62
+ cursor.execute(f"SELECT lat, lon FROM {table} WHERE lat BETWEEN {lat - 0.3} AND {lat + 0.3} AND lon BETWEEN {long - 0.3} AND {long + 0.3}")
63
+ results = cursor.fetchall()
64
+ return results[0]
climateqa/engine/talk_to_data/vanna_class.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from vanna.base import VannaBase
2
+ from pinecone import Pinecone
3
+ from climateqa.engine.embeddings import get_embeddings_function
4
+ import pandas as pd
5
+ import hashlib
6
+
7
+ class MyCustomVectorDB(VannaBase):
8
+
9
+ """
10
+ VectorDB class for storing and retrieving vectors from Pinecone.
11
+
12
+ args :
13
+ config (dict) : Configuration dictionary containing the Pinecone API key and the index name :
14
+ - pc_api_key (str) : Pinecone API key
15
+ - index_name (str) : Pinecone index name
16
+ - top_k (int) : Number of top results to return (default = 2)
17
+
18
+ """
19
+
20
+ def __init__(self,config):
21
+ super().__init__(config = config)
22
+ try :
23
+ self.api_key = config.get('pc_api_key')
24
+ self.index_name = config.get('index_name')
25
+ except :
26
+ raise Exception("Please provide the Pinecone API key and the index name")
27
+
28
+ self.pc = Pinecone(api_key = self.api_key)
29
+ self.index = self.pc.Index(self.index_name)
30
+ self.top_k = config.get('top_k', 2)
31
+ self.embeddings = get_embeddings_function()
32
+
33
+
34
+ def check_embedding(self, id, namespace):
35
+ fetched = self.index.fetch(ids = [id], namespace = namespace)
36
+ if fetched['vectors'] == {}:
37
+ return False
38
+ return True
39
+
40
+ def generate_hash_id(self, data: str) -> str:
41
+ """
42
+ Generate a unique hash ID for the given data.
43
+
44
+ Args:
45
+ data (str): The input data to hash (e.g., a concatenated string of user attributes).
46
+
47
+ Returns:
48
+ str: A unique hash ID as a hexadecimal string.
49
+ """
50
+
51
+ data_bytes = data.encode('utf-8')
52
+ hash_object = hashlib.sha256(data_bytes)
53
+ hash_id = hash_object.hexdigest()
54
+
55
+ return hash_id
56
+
57
+ def add_ddl(self, ddl: str, **kwargs) -> str:
58
+ id = self.generate_hash_id(ddl) + '_ddl'
59
+
60
+ if self.check_embedding(id, 'ddl'):
61
+ print(f"DDL having id {id} already exists")
62
+ return id
63
+
64
+ self.index.upsert(
65
+ vectors = [(id, self.embeddings.embed_query(ddl), {'ddl': ddl})],
66
+ namespace = 'ddl'
67
+ )
68
+
69
+ return id
70
+
71
+ def add_documentation(self, doc: str, **kwargs) -> str:
72
+ id = self.generate_hash_id(doc) + '_doc'
73
+
74
+ if self.check_embedding(id, 'documentation'):
75
+ print(f"Documentation having id {id} already exists")
76
+ return id
77
+
78
+ self.index.upsert(
79
+ vectors = [(id, self.embeddings.embed_query(doc), {'doc': doc})],
80
+ namespace = 'documentation'
81
+ )
82
+
83
+ return id
84
+
85
+ def add_question_sql(self, question: str, sql: str, **kwargs) -> str:
86
+ id = self.generate_hash_id(question) + '_sql'
87
+
88
+ if self.check_embedding(id, 'question_sql'):
89
+ print(f"Question-SQL pair having id {id} already exists")
90
+ return id
91
+
92
+ self.index.upsert(
93
+ vectors = [(id, self.embeddings.embed_query(question + sql), {'question': question, 'sql': sql})],
94
+ namespace = 'question_sql'
95
+ )
96
+
97
+ return id
98
+
99
+ def get_related_ddl(self, question: str, **kwargs) -> list:
100
+ res = self.index.query(
101
+ vector=self.embeddings.embed_query(question),
102
+ top_k=self.top_k,
103
+ namespace='ddl',
104
+ include_metadata=True
105
+ )
106
+
107
+ return [match['metadata']['ddl'] for match in res['matches']]
108
+
109
+ def get_related_documentation(self, question: str, **kwargs) -> list:
110
+ res = self.index.query(
111
+ vector=self.embeddings.embed_query(question),
112
+ top_k=self.top_k,
113
+ namespace='documentation',
114
+ include_metadata=True
115
+ )
116
+
117
+ return [match['metadata']['doc'] for match in res['matches']]
118
+
119
+ def get_similar_question_sql(self, question: str, **kwargs) -> list:
120
+ res = self.index.query(
121
+ vector=self.embeddings.embed_query(question),
122
+ top_k=self.top_k,
123
+ namespace='question_sql',
124
+ include_metadata=True
125
+ )
126
+
127
+ return [(match['metadata']['question'], match['metadata']['sql']) for match in res['matches']]
128
+
129
+ def get_training_data(self, **kwargs) -> pd.DataFrame:
130
+
131
+ list_of_data = []
132
+
133
+ namespaces = ['ddl', 'documentation', 'question_sql']
134
+
135
+ for namespace in namespaces:
136
+
137
+ data = self.index.query(
138
+ top_k=10000,
139
+ namespace=namespace,
140
+ include_metadata=True,
141
+ include_values=False
142
+ )
143
+
144
+ for match in data['matches']:
145
+ list_of_data.append(match['metadata'])
146
+
147
+ return pd.DataFrame(list_of_data)
148
+
149
+
150
+
151
+ def remove_training_data(self, id: str, **kwargs) -> bool:
152
+ if id.endswith("_ddl"):
153
+ self.Index.delete(ids=[id], namespace="_ddl")
154
+ return True
155
+ if id.endswith("_sql"):
156
+ self.index.delete(ids=[id], namespace="_sql")
157
+ return True
158
+
159
+ if id.endswith("_doc"):
160
+ self.Index.delete(ids=[id], namespace="_doc")
161
+ return True
162
+
163
+ return False
164
+
165
+ def generate_embedding(self, text, **kwargs):
166
+ # Implement the method here
167
+ pass
168
+
169
+
170
+ def get_sql_prompt(
171
+ self,
172
+ initial_prompt : str,
173
+ question: str,
174
+ question_sql_list: list,
175
+ ddl_list: list,
176
+ doc_list: list,
177
+ **kwargs,
178
+ ):
179
+ """
180
+ Example:
181
+ ```python
182
+ vn.get_sql_prompt(
183
+ question="What are the top 10 customers by sales?",
184
+ question_sql_list=[{"question": "What are the top 10 customers by sales?", "sql": "SELECT * FROM customers ORDER BY sales DESC LIMIT 10"}],
185
+ ddl_list=["CREATE TABLE customers (id INT, name TEXT, sales DECIMAL)"],
186
+ doc_list=["The customers table contains information about customers and their sales."],
187
+ )
188
+
189
+ ```
190
+
191
+ This method is used to generate a prompt for the LLM to generate SQL.
192
+
193
+ Args:
194
+ question (str): The question to generate SQL for.
195
+ question_sql_list (list): A list of questions and their corresponding SQL statements.
196
+ ddl_list (list): A list of DDL statements.
197
+ doc_list (list): A list of documentation.
198
+
199
+ Returns:
200
+ any: The prompt for the LLM to generate SQL.
201
+ """
202
+
203
+ if initial_prompt is None:
204
+ initial_prompt = f"You are a {self.dialect} expert. " + \
205
+ "Please help to generate a SQL query to answer the question. Your response should ONLY be based on the given context and follow the response guidelines and format instructions. "
206
+
207
+ initial_prompt = self.add_ddl_to_prompt(
208
+ initial_prompt, ddl_list, max_tokens=self.max_tokens
209
+ )
210
+
211
+ if self.static_documentation != "":
212
+ doc_list.append(self.static_documentation)
213
+
214
+ initial_prompt = self.add_documentation_to_prompt(
215
+ initial_prompt, doc_list, max_tokens=self.max_tokens
216
+ )
217
+
218
+ # initial_prompt = self.add_sql_to_prompt(
219
+ # initial_prompt, question_sql_list, max_tokens=self.max_tokens
220
+ # )
221
+
222
+
223
+ initial_prompt += (
224
+ "===Response Guidelines \n"
225
+ "1. If the provided context is sufficient, please generate a valid SQL query without any explanations for the question. \n"
226
+ "2. If the provided context is almost sufficient but requires knowledge of a specific string in a particular column, please generate an intermediate SQL query to find the distinct strings in that column. Prepend the query with a comment saying intermediate_sql \n"
227
+ "3. If the provided context is insufficient, please give a sql query based on your knowledge and the context provided. \n"
228
+ "4. Please use the most relevant table(s). \n"
229
+ "5. If the question has been asked and answered before, please repeat the answer exactly as it was given before. \n"
230
+ f"6. Ensure that the output SQL is {self.dialect}-compliant and executable, and free of syntax errors. \n"
231
+ f"7. Add a description of the table in the result of the sql query, and latitude, logitude if relevant. \n"
232
+ # "7. Add a description of the table in the result of the sql query."
233
+ # "7. If the question is about a specific latitude, longitude, query an interval of 0.3 and keep only the first set of coordinate. \n"
234
+ # "7. Table names should be included in the result of the sql query. Use for example Mean_winter_temperature AS table_name in the query \n"
235
+ )
236
+
237
+
238
+ message_log = [self.system_message(initial_prompt)]
239
+
240
+ for example in question_sql_list:
241
+ if example is None:
242
+ print("example is None")
243
+ else:
244
+ if example is not None and "question" in example and "sql" in example:
245
+ message_log.append(self.user_message(example["question"]))
246
+ message_log.append(self.assistant_message(example["sql"]))
247
+
248
+ message_log.append(self.user_message(question))
249
+
250
+ return message_log
251
+
252
+
253
+ # def get_sql_prompt(
254
+ # self,
255
+ # initial_prompt : str,
256
+ # question: str,
257
+ # question_sql_list: list,
258
+ # ddl_list: list,
259
+ # doc_list: list,
260
+ # **kwargs,
261
+ # ):
262
+ # """
263
+ # Example:
264
+ # ```python
265
+ # vn.get_sql_prompt(
266
+ # question="What are the top 10 customers by sales?",
267
+ # question_sql_list=[{"question": "What are the top 10 customers by sales?", "sql": "SELECT * FROM customers ORDER BY sales DESC LIMIT 10"}],
268
+ # ddl_list=["CREATE TABLE customers (id INT, name TEXT, sales DECIMAL)"],
269
+ # doc_list=["The customers table contains information about customers and their sales."],
270
+ # )
271
+
272
+ # ```
273
+
274
+ # This method is used to generate a prompt for the LLM to generate SQL.
275
+
276
+ # Args:
277
+ # question (str): The question to generate SQL for.
278
+ # question_sql_list (list): A list of questions and their corresponding SQL statements.
279
+ # ddl_list (list): A list of DDL statements.
280
+ # doc_list (list): A list of documentation.
281
+
282
+ # Returns:
283
+ # any: The prompt for the LLM to generate SQL.
284
+ # """
285
+
286
+ # if initial_prompt is None:
287
+ # initial_prompt = f"You are a {self.dialect} expert. " + \
288
+ # "Please help to generate a SQL query to answer the question. Your response should ONLY be based on the given context and follow the response guidelines and format instructions. "
289
+
290
+ # initial_prompt = self.add_ddl_to_prompt(
291
+ # initial_prompt, ddl_list, max_tokens=self.max_tokens
292
+ # )
293
+
294
+ # if self.static_documentation != "":
295
+ # doc_list.append(self.static_documentation)
296
+
297
+ # initial_prompt = self.add_documentation_to_prompt(
298
+ # initial_prompt, doc_list, max_tokens=self.max_tokens
299
+ # )
300
+
301
+ # initial_prompt += (
302
+ # "===Response Guidelines \n"
303
+ # "1. If the provided context is sufficient, please generate a valid SQL query without any explanations for the question. \n"
304
+ # "2. If the provided context is almost sufficient but requires knowledge of a specific string in a particular column, please generate an intermediate SQL query to find the distinct strings in that column. Prepend the query with a comment saying intermediate_sql \n"
305
+ # "3. If the provided context is insufficient, please explain why it can't be generated. \n"
306
+ # "4. Please use the most relevant table(s). \n"
307
+ # "5. If the question has been asked and answered before, please repeat the answer exactly as it was given before. \n"
308
+ # f"6. Ensure that the output SQL is {self.dialect}-compliant and executable, and free of syntax errors. \n"
309
+ # )
310
+
311
+ # message_log = [self.system_message(initial_prompt)]
312
+
313
+ # for example in question_sql_list:
314
+ # if example is None:
315
+ # print("example is None")
316
+ # else:
317
+ # if example is not None and "question" in example and "sql" in example:
318
+ # message_log.append(self.user_message(example["question"]))
319
+ # message_log.append(self.assistant_message(example["sql"]))
320
+
321
+ # message_log.append(self.user_message(question))
322
+
323
+ # return message_log
requirements.txt CHANGED
@@ -19,3 +19,5 @@ langchain-community==0.2
19
  msal==1.31
20
  matplotlib==3.9.2
21
  gradio-modal==0.0.4
 
 
 
19
  msal==1.31
20
  matplotlib==3.9.2
21
  gradio-modal==0.0.4
22
+ vanna==0.7.5
23
+ geopy==2.4.1
style.css CHANGED
@@ -606,3 +606,8 @@ a {
606
  #checkbox-config:checked {
607
  display: block;
608
  }
 
 
 
 
 
 
606
  #checkbox-config:checked {
607
  display: block;
608
  }
609
+
610
+ #vanna-display {
611
+ height: 400px;
612
+ overflow-y: auto;
613
+ }