timeki commited on
Commit
6991e90
·
1 Parent(s): e32213f

WIP Set up demo vanna

Browse files
.gitignore CHANGED
@@ -11,3 +11,6 @@ notebooks/
11
 
12
  data/
13
  sandbox/
 
 
 
 
11
 
12
  data/
13
  sandbox/
14
+
15
+ climateqa/talk_to_data/database/
16
+ *.db
app.py CHANGED
@@ -140,6 +140,9 @@ def cqa_tab(tab_name):
140
  "<h2>There are no graphs to be displayed at the moment. Try asking another question.</h2>",
141
  elem_id="graphs-container"
142
  )
 
 
 
143
  return {
144
  "chatbot": chatbot,
145
  "textbox": textbox,
@@ -160,7 +163,8 @@ def cqa_tab(tab_name):
160
  "tab_figures": tab_figures,
161
  "tab_graphs": tab_graphs,
162
  "tab_papers": tab_papers,
163
- "graph_container": graphs_container
 
164
  }
165
 
166
 
@@ -190,6 +194,7 @@ def event_handling(
190
  tab_graphs = main_tab_components["tab_graphs"]
191
  tab_papers = main_tab_components["tab_papers"]
192
  graphs_container = main_tab_components["graph_container"]
 
193
 
194
  config_open = config_components["config_open"]
195
  config_modal = config_components["config_modal"]
@@ -204,7 +209,7 @@ def event_handling(
204
  close_config_modal = config_components["close_config_modal_button"]
205
 
206
  new_sources_hmtl = gr.State([])
207
-
208
 
209
 
210
  for button in [config_button, close_config_modal]:
@@ -216,13 +221,13 @@ def event_handling(
216
  # Event for textbox
217
  (textbox
218
  .submit(start_chat, [textbox, chatbot, search_only], [textbox, tabs, chatbot, sources_raw], queue=False, api_name=f"start_chat_{textbox.elem_id}")
219
- .then(chat, [textbox, chatbot, dropdown_audience, dropdown_sources, dropdown_reports, dropdown_external_sources, search_only], [chatbot, new_sources_hmtl, output_query, output_language, new_figures, current_graphs], concurrency_limit=8, api_name=f"chat_{textbox.elem_id}")
220
  .then(finish_chat, None, [textbox], api_name=f"finish_chat_{textbox.elem_id}")
221
  )
222
  # Event for examples_hidden
223
  (examples_hidden
224
  .change(start_chat, [examples_hidden, chatbot, search_only], [examples_hidden, tabs, chatbot, sources_raw], queue=False, api_name=f"start_chat_{examples_hidden.elem_id}")
225
- .then(chat, [examples_hidden, chatbot, dropdown_audience, dropdown_sources, dropdown_reports, dropdown_external_sources, search_only], [chatbot, new_sources_hmtl, output_query, output_language, new_figures, current_graphs], concurrency_limit=8, api_name=f"chat_{examples_hidden.elem_id}")
226
  .then(finish_chat, None, [examples_hidden], api_name=f"finish_chat_{examples_hidden.elem_id}")
227
  )
228
 
@@ -239,6 +244,8 @@ def event_handling(
239
  for component in [textbox, examples_hidden]:
240
  component.submit(find_papers, [component, after, dropdown_external_sources], [papers_html, citations_network, papers_summary])
241
 
 
 
242
  def main_ui():
243
  # config_open = gr.State(True)
244
  with gr.Blocks(title="Climate Q&A", css_paths=os.getcwd()+ "/style.css", theme=theme, elem_id="main-component") as demo:
 
140
  "<h2>There are no graphs to be displayed at the moment. Try asking another question.</h2>",
141
  elem_id="graphs-container"
142
  )
143
+ with gr.Tab("Vanna", elem_id="tab-vanna", id=6) as tab_vanna:
144
+ vanna_display = gr.DataFrame([], elem_id="vanna-display")
145
+
146
  return {
147
  "chatbot": chatbot,
148
  "textbox": textbox,
 
163
  "tab_figures": tab_figures,
164
  "tab_graphs": tab_graphs,
165
  "tab_papers": tab_papers,
166
+ "graph_container": graphs_container,
167
+ "vanna_display": vanna_display
168
  }
169
 
170
 
 
194
  tab_graphs = main_tab_components["tab_graphs"]
195
  tab_papers = main_tab_components["tab_papers"]
196
  graphs_container = main_tab_components["graph_container"]
197
+ vanna_display = main_tab_components["vanna_display"]
198
 
199
  config_open = config_components["config_open"]
200
  config_modal = config_components["config_modal"]
 
209
  close_config_modal = config_components["close_config_modal_button"]
210
 
211
  new_sources_hmtl = gr.State([])
212
+ ttd_data = gr.State([])
213
 
214
 
215
  for button in [config_button, close_config_modal]:
 
221
  # Event for textbox
222
  (textbox
223
  .submit(start_chat, [textbox, chatbot, search_only], [textbox, tabs, chatbot, sources_raw], queue=False, api_name=f"start_chat_{textbox.elem_id}")
224
+ .then(chat, [textbox, chatbot, dropdown_audience, dropdown_sources, dropdown_reports, dropdown_external_sources, search_only], [chatbot, new_sources_hmtl, output_query, output_language, new_figures, current_graphs, ttd_data], concurrency_limit=8, api_name=f"chat_{textbox.elem_id}")
225
  .then(finish_chat, None, [textbox], api_name=f"finish_chat_{textbox.elem_id}")
226
  )
227
  # Event for examples_hidden
228
  (examples_hidden
229
  .change(start_chat, [examples_hidden, chatbot, search_only], [examples_hidden, tabs, chatbot, sources_raw], queue=False, api_name=f"start_chat_{examples_hidden.elem_id}")
230
+ .then(chat, [examples_hidden, chatbot, dropdown_audience, dropdown_sources, dropdown_reports, dropdown_external_sources, search_only], [chatbot, new_sources_hmtl, output_query, output_language, new_figures, current_graphs, ttd_data], concurrency_limit=8, api_name=f"chat_{examples_hidden.elem_id}")
231
  .then(finish_chat, None, [examples_hidden], api_name=f"finish_chat_{examples_hidden.elem_id}")
232
  )
233
 
 
244
  for component in [textbox, examples_hidden]:
245
  component.submit(find_papers, [component, after, dropdown_external_sources], [papers_html, citations_network, papers_summary])
246
 
247
+ ttd_data.change(lambda x: x["df_output"], inputs=[ttd_data], outputs=[vanna_display])
248
+
249
  def main_ui():
250
  # config_open = gr.State(True)
251
  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,12 @@ 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(
@@ -120,6 +126,7 @@ async def chat_stream(
120
  graphs_html = ""
121
  used_documents = []
122
  answer_message_content = ""
 
123
 
124
  # Define processing steps
125
  steps_display = {
@@ -141,6 +148,14 @@ async def chat_stream(
141
  history, used_documents = handle_retrieved_documents(
142
  event, history, used_documents
143
  )
 
 
 
 
 
 
 
 
144
  if event["event"] == "on_chain_end" and event["name"] == "answer_search" :
145
  docs = event["data"]["input"]["documents"]
146
  docs_html = convert_to_docs_to_html(docs)
@@ -183,7 +198,7 @@ async def chat_stream(
183
  sub_questions = [q["question"] for q in event["data"]["output"]["questions_list"]]
184
  history[-1].content += "Decompose question into sub-questions:\n\n - " + "\n - ".join(sub_questions)
185
 
186
- yield history, docs_html, output_query, output_language, related_contents, graphs_html
187
 
188
  except Exception as e:
189
  print(f"Event {event} has failed")
@@ -194,4 +209,4 @@ async def chat_stream(
194
  # Call the function to log interaction
195
  log_interaction_to_azure(history, output_query, sources, docs, share_client, user_id)
196
 
197
- 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
 
63
  # Main chat function
64
  async def chat_stream(
 
126
  graphs_html = ""
127
  used_documents = []
128
  answer_message_content = ""
129
+ vanna_data = {}
130
 
131
  # Define processing steps
132
  steps_display = {
 
148
  history, used_documents = handle_retrieved_documents(
149
  event, history, used_documents
150
  )
151
+ # Handle document retrieval
152
+ if event["event"] == "on_chain_end" and event["name"] in ["retrieve_documents","retrieve_local_data"] and event["data"]["output"] != None:
153
+ df_output_vanna, sql_query = handle_numerical_data(
154
+ event
155
+ )
156
+ vanna_data = {"df_output": df_output_vanna, "sql_query": sql_query}
157
+
158
+
159
  if event["event"] == "on_chain_end" and event["name"] == "answer_search" :
160
  docs = event["data"]["input"]["documents"]
161
  docs_html = convert_to_docs_to_html(docs)
 
198
  sub_questions = [q["question"] for q in event["data"]["output"]["questions_list"]]
199
  history[-1].content += "Decompose question into sub-questions:\n\n - " + "\n - ".join(sub_questions)
200
 
201
+ yield history, docs_html, output_query, output_language, related_contents, graphs_html, vanna_data
202
 
203
  except Exception as e:
204
  print(f"Event {event} has failed")
 
209
  # Call the function to log interaction
210
  log_interaction_to_azure(history, output_query, sources, docs, share_client, user_id)
211
 
212
+ 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.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/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]
50
  search_only : bool = False
51
  reports : List[str] = []
 
 
52
 
53
  def dummy(state):
54
  return
@@ -164,6 +167,7 @@ def make_graph_agent(llm, vectorstore_ipcc, vectorstore_graphs, vectorstore_regi
164
  answer_rag = make_rag_node(llm, with_docs=True)
165
  answer_rag_no_docs = make_rag_node(llm, with_docs=False)
166
  chitchat_categorize_intent = make_chitchat_intent_categorization_node(llm)
 
167
 
168
  # Define the nodes
169
  # workflow.add_node("set_defaults", set_defaults)
@@ -180,6 +184,7 @@ def make_graph_agent(llm, vectorstore_ipcc, vectorstore_graphs, vectorstore_regi
180
  workflow.add_node("retrieve_documents", retrieve_documents)
181
  workflow.add_node("answer_rag", answer_rag)
182
  workflow.add_node("answer_rag_no_docs", answer_rag_no_docs)
 
183
 
184
  # Entry point
185
  workflow.set_entry_point("categorize_intent")
@@ -235,7 +240,7 @@ def make_graph_agent(llm, vectorstore_ipcc, vectorstore_graphs, vectorstore_regi
235
 
236
  # Define the edges
237
  workflow.add_edge("translate_query", "transform_query")
238
- workflow.add_edge("transform_query", "retrieve_documents") #TODO put back
239
  # workflow.add_edge("transform_query", END) # TODO remove
240
 
241
  workflow.add_edge("retrieve_graphs", END)
@@ -245,6 +250,10 @@ def make_graph_agent(llm, vectorstore_ipcc, vectorstore_graphs, vectorstore_regi
245
  workflow.add_edge("retrieve_graphs_chitchat", END)
246
  # workflow.add_edge("retrieve_local_data", "answer_search")
247
 
 
 
 
 
248
  # Compile
249
  app = workflow.compile()
250
  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]
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
 
167
  answer_rag = make_rag_node(llm, with_docs=True)
168
  answer_rag_no_docs = make_rag_node(llm, with_docs=False)
169
  chitchat_categorize_intent = make_chitchat_intent_categorization_node(llm)
170
+ retrieve_drias_data = make_drias_retriever_node(llm)
171
 
172
  # Define the nodes
173
  # workflow.add_node("set_defaults", set_defaults)
 
184
  workflow.add_node("retrieve_documents", retrieve_documents)
185
  workflow.add_node("answer_rag", answer_rag)
186
  workflow.add_node("answer_rag_no_docs", answer_rag_no_docs)
187
+ workflow.add_node("retrieve_drias_data", retrieve_drias_data)
188
 
189
  # Entry point
190
  workflow.set_entry_point("categorize_intent")
 
240
 
241
  # Define the edges
242
  workflow.add_edge("translate_query", "transform_query")
243
+ # workflow.add_edge("transform_query", "retrieve_documents") #TODO put back
244
  # workflow.add_edge("transform_query", END) # TODO remove
245
 
246
  workflow.add_edge("retrieve_graphs", END)
 
250
  workflow.add_edge("retrieve_graphs_chitchat", END)
251
  # workflow.add_edge("retrieve_local_data", "answer_search")
252
 
253
+ workflow.add_edge("transform_query", "retrieve_drias_data")
254
+ workflow.add_edge("retrieve_drias_data", END)
255
+
256
+
257
  # Compile
258
  app = workflow.compile()
259
  return app
climateqa/talk_to_data/deprecated_vanna_remote.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from vanna.remote import VannaDefault
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(VannaDefault):
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, **kwargs):
21
+ # super().__init__(**kwargs)
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
+ # print([match['metadata']['ddl'] for match in res['matches']])
108
+
109
+ # return [match['metadata']['ddl'] for match in res['matches']]
110
+
111
+ # def get_related_documentation(self, question: str, **kwargs) -> list:
112
+ # res = self.index.query(
113
+ # vector=self.embeddings.embed_query(question),
114
+ # top_k=self.top_k,
115
+ # namespace='documentation',
116
+ # include_metadata=True
117
+ # )
118
+
119
+ # return [match['metadata']['doc'] for match in res['matches']]
120
+
121
+ # def get_similar_quetion_sql(self, question: str, **kwargs) -> list:
122
+ # res = self.index.query(
123
+ # vector=self.embeddings.embed_query(question),
124
+ # top_k=self.top_k,
125
+ # namespace='question_sql',
126
+ # include_metadata=True
127
+ # )
128
+
129
+ # return [(match['metadata']['question'], match['metadata']['sql']) for match in res['matches']]
130
+
131
+ # def get_training_data(self, **kwargs) -> pd.DataFrame:
132
+
133
+ # list_of_data = []
134
+
135
+ # namespaces = ['ddl', 'documentation', 'question_sql']
136
+
137
+ # for namespace in namespaces:
138
+
139
+ # data = self.index.query(
140
+ # top_k=10000,
141
+ # namespace=namespace,
142
+ # include_metadata=True,
143
+ # include_values=False
144
+ # )
145
+
146
+ # for match in data['matches']:
147
+ # list_of_data.append(match['metadata'])
148
+
149
+ # return pd.DataFrame(list_of_data)
150
+
151
+
152
+
153
+ # def remove_training_data(self, id: str, **kwargs) -> bool:
154
+ # if id.endswith("_ddl"):
155
+ # self.Index.delete(ids=[id], namespace="_ddl")
156
+ # return True
157
+ # if id.endswith("_sql"):
158
+ # self.index.delete(ids=[id], namespace="_sql")
159
+ # return True
160
+
161
+ # if id.endswith("_doc"):
162
+ # self.Index.delete(ids=[id], namespace="_doc")
163
+ # return True
164
+
165
+ # return False
166
+
167
+
climateqa/talk_to_data/how_to_use_main.ipynb ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": 2,
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
+ "Loading embeddings model: BAAI/bge-base-en-v1.5\n"
22
+ ]
23
+ }
24
+ ],
25
+ "source": [
26
+ "import sys\n",
27
+ "import os\n",
28
+ "sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))\n",
29
+ "\n",
30
+ "%load_ext autoreload\n",
31
+ "%autoreload 2\n",
32
+ "\n",
33
+ "from main import ask_vanna\n"
34
+ ]
35
+ },
36
+ {
37
+ "cell_type": "markdown",
38
+ "metadata": {},
39
+ "source": [
40
+ "## Create a human query"
41
+ ]
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "execution_count": 3,
46
+ "metadata": {},
47
+ "outputs": [],
48
+ "source": [
49
+ "query = \"what is the number of days where the temperature above 35 in 2050 in Marseille\"\n",
50
+ "# query = \"Compare the winter and summer precipitation in 2050 in Marseille\"\n",
51
+ "# query = \"What is the impact of climate in Bordeaux?\"\n",
52
+ "query = \"Quelle sera la température à Marseille sur les prochaines années ?\""
53
+ ]
54
+ },
55
+ {
56
+ "cell_type": "markdown",
57
+ "metadata": {},
58
+ "source": [
59
+ "## Call the function ask vanna, it gives an output of a the sql query and the dataframe of the result (tuple)"
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "execution_count": 4,
65
+ "metadata": {},
66
+ "outputs": [
67
+ {
68
+ "name": "stdout",
69
+ "output_type": "stream",
70
+ "text": [
71
+ "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 This 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 This 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",
72
+ "Using model gpt-4o-mini for 812.0 tokens (approx)\n",
73
+ "LLM Response: intermediate_sql\n",
74
+ "```sql\n",
75
+ "SELECT DISTINCT year FROM Mean_winter_temperature WHERE lat = 43.2961743 AND lon = 5.3699525\n",
76
+ "UNION\n",
77
+ "SELECT DISTINCT year FROM Mean_summer_temperature WHERE lat = 43.2961743 AND lon = 5.3699525;\n",
78
+ "```\n",
79
+ "Extracted SQL: SELECT DISTINCT year FROM Mean_winter_temperature WHERE lat = 43.2961743 AND lon = 5.3699525\n",
80
+ "UNION\n",
81
+ "SELECT DISTINCT year FROM Mean_summer_temperature WHERE lat = 43.2961743 AND lon = 5.3699525;\n",
82
+ "Running Intermediate SQL: SELECT DISTINCT year FROM Mean_winter_temperature WHERE lat = 43.2961743 AND lon = 5.3699525\n",
83
+ "UNION\n",
84
+ "SELECT DISTINCT year FROM Mean_summer_temperature WHERE lat = 43.2961743 AND lon = 5.3699525;\n",
85
+ "Final 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 This 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 This 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\\nThe following is a pandas DataFrame with the results of the intermediate SQL query SELECT DISTINCT year FROM Mean_winter_temperature WHERE lat = 43.2961743 AND lon = 5.3699525\\nUNION\\nSELECT DISTINCT year FROM Mean_summer_temperature WHERE lat = 43.2961743 AND lon = 5.3699525;: \\n| year |\\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",
86
+ "Using model gpt-4o-mini for 887.25 tokens (approx)\n",
87
+ "LLM Response: La context fourni ne contient pas d'informations sur les prévisions de température pour les prochaines années. Par conséquent, je ne peux pas générer de requête SQL pour répondre à cette question.\n",
88
+ "Couldn't run sql: Execution failed on sql 'La context fourni ne contient pas d'informations sur les prévisions de température pour les prochaines années. Par conséquent, je ne peux pas générer de requête SQL pour répondre à cette question.': near \"La\": syntax error\n"
89
+ ]
90
+ },
91
+ {
92
+ "ename": "IndexError",
93
+ "evalue": "list index out of range",
94
+ "output_type": "error",
95
+ "traceback": [
96
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
97
+ "\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)",
98
+ "Cell \u001b[0;32mIn[4], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mask_vanna\u001b[49m\u001b[43m(\u001b[49m\u001b[43mquery\u001b[49m\u001b[43m)\u001b[49m\n",
99
+ "File \u001b[0;32m~/ai4s/climate_qa/climate-question-answering/climateqa/talk_to_data/main.py:28\u001b[0m, in \u001b[0;36mask_vanna\u001b[0;34m(query)\u001b[0m\n\u001b[1;32m 26\u001b[0m answer \u001b[38;5;241m=\u001b[39m vn\u001b[38;5;241m.\u001b[39mask(user_input, print_results\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mFalse\u001b[39;00m, allow_llm_to_see_data\u001b[38;5;241m=\u001b[39m\u001b[38;5;28;01mTrue\u001b[39;00m)\n\u001b[1;32m 27\u001b[0m table \u001b[38;5;241m=\u001b[39m detectTable(answer[\u001b[38;5;241m0\u001b[39m])\n\u001b[0;32m---> 28\u001b[0m coords2 \u001b[38;5;241m=\u001b[39m nearestNeighbourSQL(db_vanna_path, coords, \u001b[43mtable\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;241;43m0\u001b[39;49m\u001b[43m]\u001b[49m)\n\u001b[1;32m 30\u001b[0m query \u001b[38;5;241m=\u001b[39m answer[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;241m.\u001b[39mreplace(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcoords[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcoords2[\u001b[38;5;241m0\u001b[39m]\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n\u001b[1;32m 31\u001b[0m sql_query \u001b[38;5;241m=\u001b[39m query\u001b[38;5;241m.\u001b[39mreplace(\u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcoords[\u001b[38;5;241m1\u001b[39m]\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m, \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;132;01m{\u001b[39;00mcoords2[\u001b[38;5;241m1\u001b[39m]\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m)\n",
100
+ "\u001b[0;31mIndexError\u001b[0m: list index out of range"
101
+ ]
102
+ }
103
+ ],
104
+ "source": [
105
+ "ask_vanna(query)"
106
+ ]
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "execution_count": null,
111
+ "metadata": {},
112
+ "outputs": [],
113
+ "source": []
114
+ }
115
+ ],
116
+ "metadata": {
117
+ "kernelspec": {
118
+ "display_name": "climateqa",
119
+ "language": "python",
120
+ "name": "python3"
121
+ },
122
+ "language_info": {
123
+ "codemirror_mode": {
124
+ "name": "ipython",
125
+ "version": 3
126
+ },
127
+ "file_extension": ".py",
128
+ "mimetype": "text/x-python",
129
+ "name": "python",
130
+ "nbconvert_exporter": "python",
131
+ "pygments_lexer": "ipython3",
132
+ "version": "3.11.9"
133
+ }
134
+ },
135
+ "nbformat": 4,
136
+ "nbformat_minor": 2
137
+ }
climateqa/talk_to_data/main.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from climateqa.talk_to_data.myVanna import MyVanna
2
+ from climateqa.talk_to_data.utils import loc2coords, detect_location_with_openai, detectTable, nearestNeighbourSQL
3
+ import sqlite3
4
+ import os
5
+ import pandas as pd
6
+
7
+
8
+
9
+ OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
10
+ PC_API_KEY = os.getenv('VANNA_PINECONE_API_KEY')
11
+ INDEX_NAME = os.getenv('VANNA_INDEX_NAME')
12
+ VANNA_MODEL = os.getenv('VANNA_MODEL')
13
+
14
+
15
+ #Vanna object
16
+ vn = MyVanna(config = {"temperature": 0, "api_key": OPENAI_API_KEY, 'model': VANNA_MODEL, 'pc_api_key': PC_API_KEY, 'index_name': INDEX_NAME})
17
+ db_vanna_path = os.path.join(os.path.dirname(__file__), "database/drias.db")
18
+ vn.connect_to_sqlite(db_vanna_path)
19
+
20
+
21
+ def ask_vanna(query):
22
+ location = detect_location_with_openai(OPENAI_API_KEY, query)
23
+ if location:
24
+ coords = loc2coords(location)
25
+ user_input = query.replace(location, f"lat, long : {coords}")
26
+ answer = vn.ask(user_input, print_results=False, allow_llm_to_see_data=True)
27
+ table = detectTable(answer[0])
28
+ coords2 = nearestNeighbourSQL(db_vanna_path, coords, table[0])
29
+
30
+ query = answer[0].replace(f"{coords[0]}", f"{coords2[0]}")
31
+ sql_query = query.replace(f"{coords[1]}", f"{coords2[1]}")
32
+
33
+ db = sqlite3.connect(db_vanna_path)
34
+ result = db.cursor().execute(sql_query).fetchall()
35
+ print(result)
36
+ df = pd.DataFrame(result, columns=answer[1].columns)
37
+
38
+ else:
39
+ answer = vn.ask(query, visualize=True, print_results=False, allow_llm_to_see_data=True)
40
+ sql_query = answer[0]
41
+ df = answer[1]
42
+
43
+ return (sql_query, df)
climateqa/talk_to_data/myVanna.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ from climateqa.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/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/talk_to_data/vanna_class.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )
232
+
233
+
234
+ message_log = [self.system_message(initial_prompt)]
235
+
236
+ for example in question_sql_list:
237
+ if example is None:
238
+ print("example is None")
239
+ else:
240
+ if example is not None and "question" in example and "sql" in example:
241
+ message_log.append(self.user_message(example["question"]))
242
+ message_log.append(self.assistant_message(example["sql"]))
243
+
244
+ message_log.append(self.user_message(question))
245
+
246
+ 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
sandbox/20241104 - CQA - StepByStep CQA.ipynb CHANGED
The diff for this file is too large to render. See raw diff