armanddemasson commited on
Commit
204ecfe
·
1 Parent(s): 69f7a91

retrieve by ToC

Browse files
.gitignore CHANGED
@@ -12,4 +12,9 @@ notebooks/
12
  data/
13
  sandbox/
14
 
15
- *.db
 
 
 
 
 
 
12
  data/
13
  sandbox/
14
 
15
+ climateqa/talk_to_data/database/
16
+ *.db
17
+
18
+ data_ingestion/
19
+ .vscode
20
+ *old/
app.py CHANGED
@@ -12,9 +12,11 @@ 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
 
18
 
19
 
20
  from utils import create_user_id
@@ -67,7 +69,10 @@ vectorstore_graphs = get_pinecone_vectorstore(embeddings_function, index_name=os
67
  vectorstore_region = get_pinecone_vectorstore(embeddings_function, index_name=os.getenv("PINECONE_API_INDEX_REGION"))
68
 
69
  llm = get_llm(provider="openai",max_tokens = 1024,temperature = 0.0)
70
- reranker = get_reranker("nano")
 
 
 
71
 
72
  agent = make_graph_agent(llm=llm, vectorstore_ipcc=vectorstore, vectorstore_graphs=vectorstore_graphs, vectorstore_region = vectorstore_region, reranker=reranker, threshold_docs=0.2)
73
  agent_poc = make_graph_agent_poc(llm=llm, vectorstore_ipcc=vectorstore, vectorstore_graphs=vectorstore_graphs, vectorstore_region = vectorstore_region, reranker=reranker, threshold_docs=0)#TODO put back default 0.2
@@ -91,7 +96,7 @@ async def chat_poc(query, history, audience, sources, reports, relevant_content_
91
  # Function to update modal visibility
92
  def update_config_modal_visibility(config_open):
93
  new_config_visibility_status = not config_open
94
- return gr.update(visible=new_config_visibility_status), new_config_visibility_status
95
 
96
 
97
  def update_sources_number_display(sources_textbox, figures_cards, current_graphs, papers_html):
@@ -116,7 +121,7 @@ def cqa_tab(tab_name):
116
  with gr.Row(elem_id="chatbot-row"):
117
  # Left column - Chat interface
118
  with gr.Column(scale=2):
119
- chatbot, textbox, config_button = create_chat_interface()
120
 
121
  # Right column - Content panels
122
  with gr.Column(scale=2, variant="panel", elem_id="right-panel"):
@@ -139,7 +144,7 @@ def cqa_tab(tab_name):
139
 
140
  # Papers subtab
141
  with gr.Tab("Papers", elem_id="tab-citations", id=4) as tab_papers:
142
- papers_summary, papers_html, citations_network, papers_modal = create_papers_tab()
143
 
144
  # Graphs subtab
145
  with gr.Tab("Graphs", elem_id="tab-graphs", id=5) as tab_graphs:
@@ -147,6 +152,20 @@ def cqa_tab(tab_name):
147
  "<h2>There are no graphs to be displayed at the moment. Try asking another question.</h2>",
148
  elem_id="graphs-container"
149
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  return {
151
  "chatbot": chatbot,
152
  "textbox": textbox,
@@ -159,6 +178,7 @@ def cqa_tab(tab_name):
159
  "figures_cards": figures_cards,
160
  "gallery_component": gallery_component,
161
  "config_button": config_button,
 
162
  "papers_html": papers_html,
163
  "citations_network": citations_network,
164
  "papers_summary": papers_summary,
@@ -167,7 +187,10 @@ def cqa_tab(tab_name):
167
  "tab_figures": tab_figures,
168
  "tab_graphs": tab_graphs,
169
  "tab_papers": tab_papers,
170
- "graph_container": graphs_container
 
 
 
171
  }
172
 
173
 
@@ -188,6 +211,7 @@ def event_handling(
188
  figures_cards = main_tab_components["figures_cards"]
189
  gallery_component = main_tab_components["gallery_component"]
190
  config_button = main_tab_components["config_button"]
 
191
  papers_html = main_tab_components["papers_html"]
192
  citations_network = main_tab_components["citations_network"]
193
  papers_summary = main_tab_components["papers_summary"]
@@ -197,6 +221,10 @@ def event_handling(
197
  tab_graphs = main_tab_components["tab_graphs"]
198
  tab_papers = main_tab_components["tab_papers"]
199
  graphs_container = main_tab_components["graph_container"]
 
 
 
 
200
 
201
  config_open = config_components["config_open"]
202
  config_modal = config_components["config_modal"]
@@ -211,8 +239,8 @@ def event_handling(
211
  close_config_modal = config_components["close_config_modal_button"]
212
 
213
  new_sources_hmtl = gr.State([])
214
-
215
- print("textbox id : ", textbox.elem_id)
216
 
217
  for button in [config_button, close_config_modal]:
218
  button.click(
@@ -262,11 +290,14 @@ def event_handling(
262
  component.change(update_sources_number_display, [sources_textbox, figures_cards, current_graphs, papers_html], [tab_recommended_content, tab_sources, tab_figures, tab_graphs, tab_papers])
263
 
264
  # Search for papers
265
- for component in [textbox, examples_hidden]:
266
  component.submit(find_papers, [component, after, dropdown_external_sources], [papers_html, citations_network, papers_summary])
267
-
268
 
269
 
 
 
 
270
 
271
  def main_ui():
272
  # config_open = gr.State(True)
@@ -280,7 +311,7 @@ def main_ui():
280
  create_about_tab()
281
 
282
  event_handling(cqa_components, config_components, tab_name = 'ClimateQ&A')
283
- event_handling(local_cqa_components, config_components, tab_name = 'Beta - POC Adapt\'Action')
284
 
285
  demo.queue()
286
 
 
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
19
+ from gradio_modal import Modal
20
 
21
 
22
  from utils import create_user_id
 
69
  vectorstore_region = get_pinecone_vectorstore(embeddings_function, index_name=os.getenv("PINECONE_API_INDEX_REGION"))
70
 
71
  llm = get_llm(provider="openai",max_tokens = 1024,temperature = 0.0)
72
+ if os.environ["GRADIO_ENV"] == "local":
73
+ reranker = get_reranker("nano")
74
+ else :
75
+ reranker = get_reranker("large")
76
 
77
  agent = make_graph_agent(llm=llm, vectorstore_ipcc=vectorstore, vectorstore_graphs=vectorstore_graphs, vectorstore_region = vectorstore_region, reranker=reranker, threshold_docs=0.2)
78
  agent_poc = make_graph_agent_poc(llm=llm, vectorstore_ipcc=vectorstore, vectorstore_graphs=vectorstore_graphs, vectorstore_region = vectorstore_region, reranker=reranker, threshold_docs=0)#TODO put back default 0.2
 
96
  # Function to update modal visibility
97
  def update_config_modal_visibility(config_open):
98
  new_config_visibility_status = not config_open
99
+ return Modal(visible=new_config_visibility_status), new_config_visibility_status
100
 
101
 
102
  def update_sources_number_display(sources_textbox, figures_cards, current_graphs, papers_html):
 
121
  with gr.Row(elem_id="chatbot-row"):
122
  # Left column - Chat interface
123
  with gr.Column(scale=2):
124
+ chatbot, textbox, config_button = create_chat_interface(tab_name)
125
 
126
  # Right column - Content panels
127
  with gr.Column(scale=2, variant="panel", elem_id="right-panel"):
 
144
 
145
  # Papers subtab
146
  with gr.Tab("Papers", elem_id="tab-citations", id=4) as tab_papers:
147
+ papers_direct_search, papers_summary, papers_html, citations_network, papers_modal = create_papers_tab()
148
 
149
  # Graphs subtab
150
  with gr.Tab("Graphs", elem_id="tab-graphs", id=5) as tab_graphs:
 
152
  "<h2>There are no graphs to be displayed at the moment. Try asking another question.</h2>",
153
  elem_id="graphs-container"
154
  )
155
+ with gr.Tab("DRIAS", elem_id="tab-vanna", id=6) as tab_vanna:
156
+ vanna_direct_question = gr.Textbox(label="Direct Question", placeholder="You can write direct question here",elem_id="direct-question", interactive=True)
157
+ with gr.Accordion("Details",elem_id = 'vanna-details', open=False) as vanna_details :
158
+ vanna_sql_query = gr.Textbox(label="SQL Query Used", elem_id="sql-query", interactive=False)
159
+ show_vanna_table = gr.Button("Show Table", elem_id="show-table")
160
+ with Modal(visible=False) as vanna_table_modal:
161
+ vanna_table = gr.DataFrame([], elem_id="vanna-table")
162
+ close_vanna_modal = gr.Button("Close", elem_id="close-vanna-modal")
163
+ close_vanna_modal.click(lambda: Modal(visible=False),None, [vanna_table_modal])
164
+ show_vanna_table.click(lambda: Modal(visible=True),None ,[vanna_table_modal])
165
+
166
+ vanna_display = gr.Plot()
167
+ vanna_direct_question.submit(ask_vanna, [vanna_direct_question], [vanna_sql_query ,vanna_table, vanna_display])
168
+
169
  return {
170
  "chatbot": chatbot,
171
  "textbox": textbox,
 
178
  "figures_cards": figures_cards,
179
  "gallery_component": gallery_component,
180
  "config_button": config_button,
181
+ "papers_direct_search" : papers_direct_search,
182
  "papers_html": papers_html,
183
  "citations_network": citations_network,
184
  "papers_summary": papers_summary,
 
187
  "tab_figures": tab_figures,
188
  "tab_graphs": tab_graphs,
189
  "tab_papers": tab_papers,
190
+ "graph_container": graphs_container,
191
+ "vanna_sql_query": vanna_sql_query,
192
+ "vanna_table" : vanna_table,
193
+ "vanna_display": vanna_display
194
  }
195
 
196
 
 
211
  figures_cards = main_tab_components["figures_cards"]
212
  gallery_component = main_tab_components["gallery_component"]
213
  config_button = main_tab_components["config_button"]
214
+ papers_direct_search = main_tab_components["papers_direct_search"]
215
  papers_html = main_tab_components["papers_html"]
216
  citations_network = main_tab_components["citations_network"]
217
  papers_summary = main_tab_components["papers_summary"]
 
221
  tab_graphs = main_tab_components["tab_graphs"]
222
  tab_papers = main_tab_components["tab_papers"]
223
  graphs_container = main_tab_components["graph_container"]
224
+ vanna_sql_query = main_tab_components["vanna_sql_query"]
225
+ vanna_table = main_tab_components["vanna_table"]
226
+ vanna_display = main_tab_components["vanna_display"]
227
+
228
 
229
  config_open = config_components["config_open"]
230
  config_modal = config_components["config_modal"]
 
239
  close_config_modal = config_components["close_config_modal_button"]
240
 
241
  new_sources_hmtl = gr.State([])
242
+ ttd_data = gr.State([])
243
+
244
 
245
  for button in [config_button, close_config_modal]:
246
  button.click(
 
290
  component.change(update_sources_number_display, [sources_textbox, figures_cards, current_graphs, papers_html], [tab_recommended_content, tab_sources, tab_figures, tab_graphs, tab_papers])
291
 
292
  # Search for papers
293
+ for component in [textbox, examples_hidden, papers_direct_search]:
294
  component.submit(find_papers, [component, after, dropdown_external_sources], [papers_html, citations_network, papers_summary])
295
+
296
 
297
 
298
+ if tab_name == "Beta - POC Adapt'Action":
299
+ # Drias search
300
+ textbox.submit(ask_vanna, [textbox], [vanna_sql_query ,vanna_table, vanna_display])
301
 
302
  def main_ui():
303
  # config_open = gr.State(True)
 
311
  create_about_tab()
312
 
313
  event_handling(cqa_components, config_components, tab_name = 'ClimateQ&A')
314
+ event_handling(local_cqa_components, config_components, tab_name = "Beta - POC Adapt'Action")
315
 
316
  demo.queue()
317
 
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, fig = 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
@@ -29,7 +29,7 @@ class IntentCategorizer(BaseModel):
29
  Examples:
30
  - ai_impact = Environmental impacts of AI: "What are the environmental impacts of AI", "How does AI affect the environment"
31
  - search = Searching for any quesiton about climate change, energy, biodiversity, nature, and everything we can find the IPCC or IPBES reports or scientific papers,
32
- - chitchat = Any general question that is not related to the environment or climate change or just conversational, or if you don't think searching the IPCC or IPBES reports would be relevant
33
  """,
34
  # - geo_info = Geolocated info about climate change: Any question where the user wants to know localized impacts of climate change, eg: "What will be the temperature in Marseille in 2050"
35
  # - esg = Any question about the ESG regulation, frameworks and standards like the CSRD, TCFD, SASB, GRI, CDP, etc.
@@ -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"]})
 
29
  Examples:
30
  - ai_impact = Environmental impacts of AI: "What are the environmental impacts of AI", "How does AI affect the environment"
31
  - search = Searching for any quesiton about climate change, energy, biodiversity, nature, and everything we can find the IPCC or IPBES reports or scientific papers,
32
+ - chitchat = Any general question that is not related to the environment or climate change or just conversational, or if you don't think searching the IPCC or IPBES reports would be relevant. If it can be interprated as a climate related question, please use the search intent.
33
  """,
34
  # - geo_info = Geolocated info about climate change: Any question where the user wants to know localized impacts of climate change, eg: "What will be the temperature in Marseille in 2050"
35
  # - esg = Any question about the ESG regulation, frameworks and standards like the CSRD, TCFD, SASB, GRI, CDP, etc.
 
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/prompts.py CHANGED
@@ -66,10 +66,11 @@ You are ClimateQ&A, an AI Assistant created by Ekimetrics. You are given a quest
66
  Guidelines:
67
  - If the passages have useful facts or numbers, use them in your answer.
68
  - When you use information from a passage, mention where it came from by using [Doc i] at the end of the sentence. i stands for the number of the document.
69
- - You will receive passages from different reports, eg IPCC and PPCP, make separate paragraphs and specify the source of the information in your answer, eg "According to IPCC, ...".
70
- - The different sources are IPCC, IPBES, PPCP (for Plan Climat Air Energie Territorial de Paris), PBDP (for Plan Biodiversité de Paris), Acclimaterra.
 
71
  - Do not mention that you are using specific extract documents, but mention only the source information. "According to IPCC, ..." rather than "According to the provided document from IPCC ..."
72
- - Make a clear distinction between information from IPCC, IPBES, Acclimaterra that are scientific reports and PPCP, PBDP that are strategic reports. Strategic reports should not be taken has verified facts, but as political or strategic decisions.
73
  - If the same thing is said in more than one document, you can mention all of them like this: [Doc i, Doc j, Doc k]
74
  - Do not just summarize each passage one by one. Group your summaries to highlight the key parts in the explanation.
75
  - If it makes sense, use bullet points and lists to make your answers easier to understand.
@@ -197,4 +198,58 @@ Graphs and their HTML embedding:
197
  {format_instructions}
198
 
199
  Output the result as json with a key "graphs" containing a list of dictionaries of the relevant graphs with keys 'embedding', 'category', and 'source'. Do not modify the graph HTML embedding, the category or the source. Do not put any message or text before or after the JSON output.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
200
  """
 
66
  Guidelines:
67
  - If the passages have useful facts or numbers, use them in your answer.
68
  - When you use information from a passage, mention where it came from by using [Doc i] at the end of the sentence. i stands for the number of the document.
69
+ - You will receive passages from different reports, e.g., IPCC and PPCP. Make separate paragraphs and specify the source of the information in your answer, e.g., "According to IPCC, ...".
70
+ - The different sources are IPCC, IPBES, PPCP (for Plan Climat Air Energie Territorial de Paris), PBDP (for Plan Biodiversité de Paris), Acclimaterra (Rapport scientifique de la région Nouvelle Aquitaine en France).
71
+ - If the reports are local (like PPCP, PBDP, Acclimaterra), consider that the information is specific to the region and not global. If the document is about a nearby region (for example, an extract from Acclimaterra for a question about Britain), explicitly state the concerned region.
72
  - Do not mention that you are using specific extract documents, but mention only the source information. "According to IPCC, ..." rather than "According to the provided document from IPCC ..."
73
+ - Make a clear distinction between information from IPCC, IPBES, Acclimaterra that are scientific reports and PPCP, PBDP that are strategic reports. Strategic reports should not be taken as verified facts, but as political or strategic decisions.
74
  - If the same thing is said in more than one document, you can mention all of them like this: [Doc i, Doc j, Doc k]
75
  - Do not just summarize each passage one by one. Group your summaries to highlight the key parts in the explanation.
76
  - If it makes sense, use bullet points and lists to make your answers easier to understand.
 
198
  {format_instructions}
199
 
200
  Output the result as json with a key "graphs" containing a list of dictionaries of the relevant graphs with keys 'embedding', 'category', and 'source'. Do not modify the graph HTML embedding, the category or the source. Do not put any message or text before or after the JSON output.
201
+ """
202
+
203
+ retrieve_chapter_prompt_template = """A partir de la question de l'utilisateur et d'une liste de documents avec leurs tables des matières, retrouve les 5 chapitres de niveau 0 les plus pertinents qui pourraient aider à répondre à la question tout en prenant bien en compte leurs sous-chapitres.
204
+
205
+
206
+ La table des matières est structurée de cette façon :
207
+ {{
208
+ "level": 0,
209
+ "Chapitre 1": {{}},
210
+ "Chapitre 2" : {{
211
+ "level": 1,
212
+ "Chapitre 2.1": {{
213
+ ...
214
+ }}
215
+ }},
216
+ }}
217
+
218
+ Ici level correspond au niveau du chapitre. Ici par exemple Chapitre 1 et Chapitre 2 sont au niveau 0, et Chapitre 2.1 est au niveau 1
219
+
220
+ -----------------------
221
+ Suis impérativement cette guideline ci-dessous.
222
+
223
+ ### Guidelines ###
224
+ - Retiens bien la liste complète des documents.
225
+ - Chaque chapitre doit conserver **EXACTEMENT** le niveau qui lui est attribué dans la table des matières. **NE MODIFIE PAS LES NIVEAUX.**
226
+ - Vérifie systématiquement le niveau d’un chapitre avant de l’inclure dans la réponse.
227
+ - Retourne un résultat **JSON valide**.
228
+
229
+ --------------------
230
+ Question de l'utilisateur :
231
+ {query}
232
+
233
+ Liste des documents avec leurs tables des matières :
234
+ {doc_list}
235
+
236
+ --------------------
237
+
238
+ Retourne le résultat en JSON contenant une liste des chapitres pertinents avec les clés suivantes sans l'indicateur markdown du json:
239
+ - "document" : le document contenant le chapitre
240
+ - "chapter" : le titre du chapitre
241
+
242
+ **IMPORTANT : Assure-toi que les niveaux dans la réponse sont exactement ceux de la table des matières.**
243
+
244
+ Exemple de réponse JSON :
245
+ [
246
+ {{
247
+ "document": "Document A",
248
+ "chapter": "Chapitre 1",
249
+ }},
250
+ {{
251
+ "document": "Document B",
252
+ "chapter": "Chapitre 1.1",
253
+ }}
254
+ ]
255
  """
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/chains/retrieve_documents.py CHANGED
@@ -15,6 +15,14 @@ from ..utils import log_event
15
  from langchain_core.vectorstores import VectorStore
16
  from typing import List
17
  from langchain_core.documents.base import Document
 
 
 
 
 
 
 
 
18
  import asyncio
19
 
20
  from typing import Any, Dict, List, Tuple
@@ -232,8 +240,7 @@ async def get_IPCC_relevant_documents(
232
  "chunk_type":"text",
233
  "report_type": { "$nin":["SPM"]},
234
  }
235
- k_full = k_total - len(docs_summaries)
236
- docs_full = vectorstore.similarity_search_with_score(query=query,filter = filters_full,k = k_full)
237
 
238
  if search_figures:
239
  # Images
@@ -280,6 +287,7 @@ async def retrieve_documents(
280
  source_type: str,
281
  vectorstore: VectorStore,
282
  reranker: Any,
 
283
  search_figures: bool = False,
284
  search_only: bool = False,
285
  reports: list = [],
@@ -287,7 +295,9 @@ async def retrieve_documents(
287
  k_images_by_question: int = 5,
288
  k_before_reranking: int = 100,
289
  k_by_question: int = 5,
290
- k_summary_by_question: int = 3
 
 
291
  ) -> Tuple[List[Document], List[Document]]:
292
  """
293
  Unpack the first question of the remaining questions, and retrieve and rerank corresponding documents, based on the question and selected_sources
@@ -317,6 +327,7 @@ async def retrieve_documents(
317
 
318
  print(f"""---- Retrieve documents from {current_question["source_type"]}----""")
319
 
 
320
  if source_type == "IPx":
321
  docs_question_dict = await get_IPCC_relevant_documents(
322
  query = question,
@@ -332,19 +343,39 @@ async def retrieve_documents(
332
  reports = reports,
333
  )
334
 
335
- if source_type == "POC":
336
- docs_question_dict = await get_POC_relevant_documents(
337
- query = question,
338
- vectorstore=vectorstore,
339
- search_figures = search_figures,
340
- sources = sources,
341
- threshold = 0.5,
342
- search_only = search_only,
343
- reports = reports,
344
- min_size= 200,
345
- k_documents= k_before_reranking,
346
- k_images= k_by_question
347
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
348
 
349
  # Rerank
350
  if reranker is not None and rerank_by_question:
@@ -370,24 +401,44 @@ async def retrieve_documents(
370
  return docs_question, images_question
371
 
372
 
373
- async def retrieve_documents_for_all_questions(state, config, source_type, to_handle_questions_index, vectorstore, reranker, rerank_by_question=True, k_final=15, k_before_reranking=100):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  """
375
  Retrieve documents in parallel for all questions.
376
  """
377
  # to_handle_questions_index = [x for x in state["questions_list"] if x["source_type"] == "IPx"]
378
 
379
  # TODO split les questions selon le type de sources dans le state question + conditions sur le nombre de questions traités par type de source
380
- docs = state.get("documents", [])
381
- related_content = state.get("related_content", [])
382
- search_figures = "Figures (IPCC/IPBES)" in state["relevant_content_sources_selection"]
383
- search_only = state["search_only"]
384
- reports = state["reports"]
385
-
386
- k_by_question = k_final // state["n_questions"]["total"]
387
- k_summary_by_question = _get_k_summary_by_question(state["n_questions"]["total"])
388
- k_images_by_question = _get_k_images_by_question(state["n_questions"]["total"])
 
 
389
  k_before_reranking=100
390
 
 
391
  tasks = [
392
  retrieve_documents(
393
  current_question=question,
@@ -402,9 +453,12 @@ async def retrieve_documents_for_all_questions(state, config, source_type, to_ha
402
  k_images_by_question=k_images_by_question,
403
  k_before_reranking=k_before_reranking,
404
  k_by_question=k_by_question,
405
- k_summary_by_question=k_summary_by_question
 
 
 
406
  )
407
- for i, question in enumerate(state["questions_list"]) if i in to_handle_questions_index
408
  ]
409
  results = await asyncio.gather(*tasks)
410
  # Combine results
@@ -420,10 +474,18 @@ def make_IPx_retriever_node(vectorstore,reranker,llm,rerank_by_question=True, k_
420
  source_type = "IPx"
421
  IPx_questions_index = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "IPx"]
422
 
423
- # return {"documents":[], "related_contents": [], "handled_questions_index": list(range(len(state["questions_list"])))} # TODO Remove
424
-
 
 
 
 
425
  state = await retrieve_documents_for_all_questions(
426
- state=state,
 
 
 
 
427
  config=config,
428
  source_type=source_type,
429
  to_handle_questions_index=IPx_questions_index,
@@ -447,6 +509,171 @@ def make_POC_retriever_node(vectorstore,reranker,llm,rerank_by_question=True, k_
447
  source_type = "POC"
448
  POC_questions_index = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "POC"]
449
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
450
  state = await retrieve_documents_for_all_questions(
451
  state=state,
452
  config=config,
@@ -457,6 +684,9 @@ def make_POC_retriever_node(vectorstore,reranker,llm,rerank_by_question=True, k_
457
  rerank_by_question=rerank_by_question,
458
  k_final=k_final,
459
  k_before_reranking=k_before_reranking,
 
 
 
460
  )
461
  return state
462
 
@@ -464,3 +694,5 @@ def make_POC_retriever_node(vectorstore,reranker,llm,rerank_by_question=True, k_
464
 
465
 
466
 
 
 
 
15
  from langchain_core.vectorstores import VectorStore
16
  from typing import List
17
  from langchain_core.documents.base import Document
18
+ from ..llm import get_llm
19
+ from .prompts import retrieve_chapter_prompt_template
20
+ from langchain_core.prompts import ChatPromptTemplate
21
+ from langchain_core.output_parsers import StrOutputParser
22
+ from ..vectorstore import get_pinecone_vectorstore
23
+ from ..embeddings import get_embeddings_function
24
+
25
+
26
  import asyncio
27
 
28
  from typing import Any, Dict, List, Tuple
 
240
  "chunk_type":"text",
241
  "report_type": { "$nin":["SPM"]},
242
  }
243
+ docs_full = vectorstore.similarity_search_with_score(query=query,filter = filters_full,k = k_total)
 
244
 
245
  if search_figures:
246
  # Images
 
287
  source_type: str,
288
  vectorstore: VectorStore,
289
  reranker: Any,
290
+ version: str = "",
291
  search_figures: bool = False,
292
  search_only: bool = False,
293
  reports: list = [],
 
295
  k_images_by_question: int = 5,
296
  k_before_reranking: int = 100,
297
  k_by_question: int = 5,
298
+ k_summary_by_question: int = 3,
299
+ tocs: list = [],
300
+ by_toc=False
301
  ) -> Tuple[List[Document], List[Document]]:
302
  """
303
  Unpack the first question of the remaining questions, and retrieve and rerank corresponding documents, based on the question and selected_sources
 
327
 
328
  print(f"""---- Retrieve documents from {current_question["source_type"]}----""")
329
 
330
+
331
  if source_type == "IPx":
332
  docs_question_dict = await get_IPCC_relevant_documents(
333
  query = question,
 
343
  reports = reports,
344
  )
345
 
346
+ # if source_type == "POC":
347
+ #
348
+
349
+ if source_type == 'POC':
350
+ if by_toc == True:
351
+ print("---- Retrieve documents by ToC----")
352
+ docs_question_dict = await get_POC_by_ToC_relevant_documents(
353
+ query=question,
354
+ tocs = tocs,
355
+ vectorstore=vectorstore,
356
+ version=version,
357
+ search_figures = search_figures,
358
+ sources = sources,
359
+ threshold = 0.5,
360
+ search_only = search_only,
361
+ reports = reports,
362
+ min_size= 200,
363
+ k_documents= k_before_reranking,
364
+ k_images= k_by_question
365
+ )
366
+ else :
367
+ docs_question_dict = await get_POC_relevant_documents(
368
+ query = question,
369
+ vectorstore=vectorstore,
370
+ search_figures = search_figures,
371
+ sources = sources,
372
+ threshold = 0.5,
373
+ search_only = search_only,
374
+ reports = reports,
375
+ min_size= 200,
376
+ k_documents= k_before_reranking,
377
+ k_images= k_by_question
378
+ )
379
 
380
  # Rerank
381
  if reranker is not None and rerank_by_question:
 
401
  return docs_question, images_question
402
 
403
 
404
+ async def retrieve_documents_for_all_questions(
405
+ search_figures,
406
+ search_only,
407
+ reports,
408
+ questions_list,
409
+ n_questions,
410
+ config,
411
+ source_type,
412
+ to_handle_questions_index,
413
+ vectorstore,
414
+ reranker,
415
+ rerank_by_question=True,
416
+ k_final=15,
417
+ k_before_reranking=100,
418
+ version: str = "",
419
+ tocs: list[dict] = [],
420
+ by_toc: bool = False
421
+ ):
422
  """
423
  Retrieve documents in parallel for all questions.
424
  """
425
  # to_handle_questions_index = [x for x in state["questions_list"] if x["source_type"] == "IPx"]
426
 
427
  # TODO split les questions selon le type de sources dans le state question + conditions sur le nombre de questions traités par type de source
428
+ # search_figures = "Figures (IPCC/IPBES)" in state["relevant_content_sources_selection"]
429
+ # search_only = state["search_only"]
430
+ # reports = state["reports"]
431
+ # questions_list = state["questions_list"]
432
+
433
+ # k_by_question = k_final // state["n_questions"]["total"]
434
+ # k_summary_by_question = _get_k_summary_by_question(state["n_questions"]["total"])
435
+ # k_images_by_question = _get_k_images_by_question(state["n_questions"]["total"])
436
+ k_by_question = k_final // n_questions
437
+ k_summary_by_question = _get_k_summary_by_question(n_questions)
438
+ k_images_by_question = _get_k_images_by_question(n_questions)
439
  k_before_reranking=100
440
 
441
+ print(f"Source type here is {source_type}")
442
  tasks = [
443
  retrieve_documents(
444
  current_question=question,
 
453
  k_images_by_question=k_images_by_question,
454
  k_before_reranking=k_before_reranking,
455
  k_by_question=k_by_question,
456
+ k_summary_by_question=k_summary_by_question,
457
+ tocs=tocs,
458
+ version=version,
459
+ by_toc=by_toc
460
  )
461
+ for i, question in enumerate(questions_list) if i in to_handle_questions_index
462
  ]
463
  results = await asyncio.gather(*tasks)
464
  # Combine results
 
474
  source_type = "IPx"
475
  IPx_questions_index = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "IPx"]
476
 
477
+ search_figures = "Figures (IPCC/IPBES)" in state["relevant_content_sources_selection"]
478
+ search_only = state["search_only"]
479
+ reports = state["reports"]
480
+ questions_list = state["questions_list"]
481
+ n_questions=state["n_questions"]["total"]
482
+
483
  state = await retrieve_documents_for_all_questions(
484
+ search_figures=search_figures,
485
+ search_only=search_only,
486
+ reports=reports,
487
+ questions_list=questions_list,
488
+ n_questions=n_questions,
489
  config=config,
490
  source_type=source_type,
491
  to_handle_questions_index=IPx_questions_index,
 
509
  source_type = "POC"
510
  POC_questions_index = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "POC"]
511
 
512
+ search_figures = "Figures (IPCC/IPBES)" in state["relevant_content_sources_selection"]
513
+ search_only = state["search_only"]
514
+ reports = state["reports"]
515
+ questions_list = state["questions_list"]
516
+ n_questions=state["n_questions"]["total"]
517
+
518
+ state = await retrieve_documents_for_all_questions(
519
+ search_figures=search_figures,
520
+ search_only=search_only,
521
+ reports=reports,
522
+ questions_list=questions_list,
523
+ n_questions=n_questions,
524
+ config=config,
525
+ source_type=source_type,
526
+ to_handle_questions_index=POC_questions_index,
527
+ vectorstore=vectorstore,
528
+ reranker=reranker,
529
+ rerank_by_question=rerank_by_question,
530
+ k_final=k_final,
531
+ k_before_reranking=k_before_reranking,
532
+ )
533
+ return state
534
+
535
+ return retrieve_POC_docs_node
536
+
537
+
538
+ # ToC Retriever
539
+ async def get_relevant_toc_level_for_query(
540
+ query: str,
541
+ tocs: list[Document],
542
+ ) -> list[dict] :
543
+
544
+ doc_list = []
545
+ for doc in tocs:
546
+ doc_name = doc[0].metadata['name']
547
+ toc = doc[0].page_content
548
+ doc_list.append({'document': doc_name, 'toc': toc})
549
+
550
+ llm = get_llm(provider="openai",max_tokens = 1024,temperature = 0.0)
551
+
552
+ prompt = ChatPromptTemplate.from_template(retrieve_chapter_prompt_template)
553
+ chain = prompt | llm | StrOutputParser()
554
+ response = chain.invoke({"query": query, "doc_list": doc_list})
555
+
556
+ try:
557
+ relevant_tocs = eval(response)
558
+ except Exception as e:
559
+ print(f" Failed to parse the result because of : {e}")
560
+
561
+ return relevant_tocs
562
+
563
+
564
+ async def get_POC_by_ToC_relevant_documents(
565
+ query: str,
566
+ tocs: list[str],
567
+ vectorstore:VectorStore,
568
+ version: str = "",
569
+ sources:list = ["Acclimaterra","PCAET","Plan Biodiversite"],
570
+ search_figures:bool = False,
571
+ search_only:bool = False,
572
+ k_documents:int = 10,
573
+ threshold:float = 0.6,
574
+ k_images: int = 5,
575
+ reports:list = [],
576
+ min_size:int = 200,
577
+ proportion: float = 0.5,
578
+ ) :
579
+ # Prepare base search kwargs
580
+ filters = {}
581
+ docs_question = []
582
+ docs_images = []
583
+
584
+ # TODO add source selection
585
+ # if len(reports) > 0:
586
+ # filters["short_name"] = {"$in":reports}
587
+ # else:
588
+ # filters["source"] = { "$in": sources}
589
+
590
+ k_documents_toc = round(k_documents * proportion)
591
+
592
+ relevant_tocs = await get_relevant_toc_level_for_query(query, tocs)
593
+
594
+ print(f"Relevant ToCs : {relevant_tocs}")
595
+ # Transform the ToC dict {"document": str, "chapter": str} into a list of string
596
+ toc_filters = [toc['chapter'] for toc in relevant_tocs]
597
+
598
+ filters_text_toc = {
599
+ **filters,
600
+ "chunk_type":"text",
601
+ "toc_level0": {"$in": toc_filters},
602
+ "version": version
603
+ # "report_type": {}, # TODO to be completed to choose the right documents / chapters according to the analysis of the question
604
+ }
605
+
606
+ docs_question = vectorstore.similarity_search_with_score(query=query,filter = filters_text_toc,k = k_documents_toc)
607
+
608
+ filters_text = {
609
+ **filters,
610
+ "chunk_type":"text",
611
+ "version": version
612
+ # "report_type": {}, # TODO to be completed to choose the right documents / chapters according to the analysis of the question
613
+ }
614
+
615
+ docs_question += vectorstore.similarity_search_with_score(query=query,filter = filters_text,k = k_documents - k_documents_toc)
616
+
617
+ # remove duplicates or almost duplicates
618
+ docs_question = remove_duplicates_chunks(docs_question)
619
+ docs_question = [x for x in docs_question if x[1] > threshold]
620
+
621
+ if search_figures:
622
+ # Images
623
+ filters_image = {
624
+ **filters,
625
+ "chunk_type":"image"
626
+ }
627
+ docs_images = vectorstore.similarity_search_with_score(query=query,filter = filters_image,k = k_images)
628
+
629
+ docs_question, docs_images = _add_metadata_and_score(docs_question), _add_metadata_and_score(docs_images)
630
+
631
+ docs_question = [x for x in docs_question if len(x.page_content) > min_size]
632
+
633
+ return {
634
+ "docs_question" : docs_question,
635
+ "docs_images" : docs_images
636
+ }
637
+
638
+
639
+ def get_ToCs(version: str) :
640
+
641
+ filters_text = {
642
+ "chunk_type":"toc",
643
+ "version": version
644
+ }
645
+ embeddings_function = get_embeddings_function()
646
+ vectorstore = get_pinecone_vectorstore(embeddings_function, index_name="climateqa-v2")
647
+ tocs = vectorstore.similarity_search_with_score(query="",filter = filters_text)
648
+
649
+ # remove duplicates or almost duplicates
650
+ tocs = remove_duplicates_chunks(tocs)
651
+
652
+ return tocs
653
+
654
+
655
+
656
+ def make_POC_by_ToC_retriever_node(
657
+ vectorstore: VectorStore,
658
+ reranker,
659
+ llm,
660
+ version: str = "",
661
+ rerank_by_question=True,
662
+ k_final=15,
663
+ k_before_reranking=100,
664
+ k_summary=5,
665
+ ):
666
+
667
+ async def retrieve_POC_docs_node(state, config):
668
+ if "POC region" not in state["relevant_content_sources_selection"] :
669
+ return {}
670
+
671
+
672
+ tocs = get_ToCs(version=version)
673
+
674
+ source_type = "POC"
675
+ POC_questions_index = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "POC"]
676
+
677
  state = await retrieve_documents_for_all_questions(
678
  state=state,
679
  config=config,
 
684
  rerank_by_question=rerank_by_question,
685
  k_final=k_final,
686
  k_before_reranking=k_before_reranking,
687
+ tocs=tocs,
688
+ version=version,
689
+ by_toc=True
690
  )
691
  return state
692
 
 
694
 
695
 
696
 
697
+
698
+
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):
@@ -39,16 +40,18 @@ class GraphState(TypedDict):
39
  n_questions : int
40
  answer: str
41
  audience: str = "experts"
42
- sources_input: List[str] = ["IPCC","IPBES"]
43
  relevant_content_sources_selection: List[str] = ["Figures (IPCC/IPBES)"]
44
  sources_auto: bool = True
45
  min_year: int = 1960
46
  max_year: int = None
47
  documents: Annotated[List[Document], operator.add]
48
- related_contents : Annotated[List[Document], operator.add]
49
- recommended_content : List[Document]
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
 
@@ -95,20 +98,10 @@ def route_based_on_relevant_docs(state,threshold_docs=0.2):
95
  def route_continue_retrieve_documents(state):
96
  index_question_ipx = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "IPx"]
97
  questions_ipx_finished = all(elem in state["handled_questions_index"] for elem in index_question_ipx)
98
- # if questions_ipx_finished and state["search_only"]:
99
- # return END
100
  if questions_ipx_finished:
101
  return "end_retrieve_IPx_documents"
102
  else:
103
  return "retrieve_documents"
104
-
105
-
106
- # if state["n_questions"]["IPx"] == len(state["handled_questions_index"]) and state["search_only"] :
107
- # return END
108
- # elif state["n_questions"]["IPx"] == len(state["handled_questions_index"]):
109
- # return "answer_search"
110
- # else :
111
- # return "retrieve_documents"
112
 
113
  def route_continue_retrieve_local_documents(state):
114
  index_question_poc = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "POC"]
@@ -120,20 +113,6 @@ def route_continue_retrieve_local_documents(state):
120
  else:
121
  return "retrieve_local_data"
122
 
123
- # if state["n_questions"]["POC"] == len(state["handled_questions_index"]) and state["search_only"] :
124
- # return END
125
- # elif state["n_questions"]["POC"] == len(state["handled_questions_index"]):
126
- # return "answer_search"
127
- # else :
128
- # return "retrieve_local_data"
129
-
130
- # if len(state["remaining_questions"]) == 0 and state["search_only"] :
131
- # return END
132
- # elif len(state["remaining_questions"]) > 0:
133
- # return "retrieve_documents"
134
- # else:
135
- # return "answer_search"
136
-
137
  def route_retrieve_documents(state):
138
  sources_to_retrieve = []
139
 
@@ -248,6 +227,7 @@ def make_graph_agent_poc(llm, vectorstore_ipcc, vectorstore_graphs, vectorstore_
248
  answer_rag = make_rag_node(llm, with_docs=True)
249
  answer_rag_no_docs = make_rag_node(llm, with_docs=False)
250
  chitchat_categorize_intent = make_chitchat_intent_categorization_node(llm)
 
251
 
252
  # Define the nodes
253
  # workflow.add_node("set_defaults", set_defaults)
@@ -266,6 +246,7 @@ def make_graph_agent_poc(llm, vectorstore_ipcc, vectorstore_graphs, vectorstore_
266
  workflow.add_node("retrieve_documents", retrieve_documents)
267
  workflow.add_node("answer_rag", answer_rag)
268
  workflow.add_node("answer_rag_no_docs", answer_rag_no_docs)
 
269
 
270
  # Entry point
271
  workflow.set_entry_point("categorize_intent")
@@ -315,6 +296,10 @@ def make_graph_agent_poc(llm, vectorstore_ipcc, vectorstore_graphs, vectorstore_
315
  workflow.add_edge("retrieve_local_data", "answer_search")
316
  workflow.add_edge("retrieve_documents", "answer_search")
317
 
 
 
 
 
318
  # Compile
319
  app = workflow.compile()
320
  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):
 
40
  n_questions : int
41
  answer: str
42
  audience: str = "experts"
43
+ sources_input: List[str] = ["IPCC","IPBES"] # Deprecated -> used only graphs that can only be OWID
44
  relevant_content_sources_selection: List[str] = ["Figures (IPCC/IPBES)"]
45
  sources_auto: bool = True
46
  min_year: int = 1960
47
  max_year: int = None
48
  documents: Annotated[List[Document], operator.add]
49
+ related_contents : Annotated[List[Document], operator.add] # Images
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
 
 
98
  def route_continue_retrieve_documents(state):
99
  index_question_ipx = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "IPx"]
100
  questions_ipx_finished = all(elem in state["handled_questions_index"] for elem in index_question_ipx)
 
 
101
  if questions_ipx_finished:
102
  return "end_retrieve_IPx_documents"
103
  else:
104
  return "retrieve_documents"
 
 
 
 
 
 
 
 
105
 
106
  def route_continue_retrieve_local_documents(state):
107
  index_question_poc = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "POC"]
 
113
  else:
114
  return "retrieve_local_data"
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  def route_retrieve_documents(state):
117
  sources_to_retrieve = []
118
 
 
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) # WIP
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)# WIP
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/main.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, detect_relevant_tables, replace_coordonates
3
+ import sqlite3
4
+ import os
5
+ import pandas as pd
6
+ from climateqa.engine.llm import get_llm
7
+
8
+ from dotenv import load_dotenv
9
+ import ast
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_llm_to_add_table_names(sql_query, llm):
28
+ sql_with_table_names = llm.invoke(f"Make the following sql query display the source table in the rows {sql_query}. Just answer the query. The answer should not include ```sql\n").content
29
+ return sql_with_table_names
30
+
31
+ def ask_llm_column_names(sql_query, llm):
32
+ 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}").content
33
+ columns_list = ast.literal_eval(columns.strip("```python\n").strip())
34
+ return columns_list
35
+
36
+ def ask_vanna(query):
37
+ try :
38
+ location = detect_location_with_openai(OPENAI_API_KEY, query)
39
+ if location:
40
+
41
+ coords = loc2coords(location)
42
+ user_input = query.lower().replace(location.lower(), f"lat, long : {coords}")
43
+
44
+ relevant_tables = detect_relevant_tables(user_input, llm)
45
+ coords_tables = [nearestNeighbourSQL(db_vanna_path, coords, relevant_tables[i]) for i in range(len(relevant_tables))]
46
+ user_input_with_coords = replace_coordonates(coords, user_input, coords_tables)
47
+
48
+ sql_query, result_dataframe, figure = vn.ask(user_input_with_coords, print_results=False, allow_llm_to_see_data=True, auto_train=False)
49
+
50
+ return sql_query, result_dataframe, figure
51
+
52
+ else :
53
+ empty_df = pd.DataFrame()
54
+ empty_fig = {}
55
+ return "", empty_df, empty_fig
56
+ except Exception as e:
57
+ print(f"Error: {e}")
58
+ empty_df = pd.DataFrame()
59
+ empty_fig = {}
60
+ 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/utils.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import openai
3
+ import pandas as pd
4
+ from geopy.geocoders import Nominatim
5
+ import sqlite3
6
+ import ast
7
+
8
+
9
+ def detect_location_with_openai(api_key, sentence):
10
+ """
11
+ Detects locations in a sentence using OpenAI's API.
12
+ """
13
+ openai.api_key = api_key
14
+
15
+ prompt = f"""
16
+ Extract all locations (cities, countries, states, or geographical areas) mentioned in the following sentence.
17
+ Return the result as a Python list. If no locations are mentioned, return an empty list.
18
+
19
+ Sentence: "{sentence}"
20
+ """
21
+
22
+ response = openai.chat.completions.create(
23
+ model="gpt-4o-mini",
24
+ messages=[
25
+ {"role": "system", "content": "You are a helpful assistant skilled in identifying locations in text."},
26
+ {"role": "user", "content": prompt}
27
+ ],
28
+ max_tokens=100,
29
+ temperature=0
30
+ )
31
+
32
+ return response.choices[0].message.content.split("\n")[1][2:-2]
33
+
34
+
35
+ def detectTable(sql_query):
36
+ pattern = r'(?i)\bFROM\s+((?:`[^`]+`|"[^"]+"|\'[^\']+\'|\w+)(?:\.(?:`[^`]+`|"[^"]+"|\'[^\']+\'|\w+))*)'
37
+ matches = re.findall(pattern, sql_query)
38
+ return matches
39
+
40
+
41
+
42
+ def loc2coords(location : str):
43
+ geolocator = Nominatim(user_agent="city_to_latlong")
44
+ location = geolocator.geocode(location)
45
+ return (location.latitude, location.longitude)
46
+
47
+
48
+ def coords2loc(coords : tuple):
49
+ geolocator = Nominatim(user_agent="coords_to_city")
50
+ try:
51
+ location = geolocator.reverse(coords)
52
+ return location.address
53
+ except Exception as e:
54
+ print(f"Error: {e}")
55
+ return "Unknown Location"
56
+
57
+
58
+ def nearestNeighbourSQL(db: str, location: tuple, table : str):
59
+ conn = sqlite3.connect(db)
60
+ long = round(location[1], 3)
61
+ lat = round(location[0], 3)
62
+ cursor = conn.cursor()
63
+ 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}")
64
+ results = cursor.fetchall()
65
+ return results[0]
66
+
67
+ def detect_relevant_tables(user_question, llm):
68
+ table_names_list = [
69
+ "Frequency_of_rainy_days_index",
70
+ "Winter_precipitation_total",
71
+ "Summer_precipitation_total",
72
+ "Annual_precipitation_total",
73
+ # "Remarkable_daily_precipitation_total_(Q99)",
74
+ "Frequency_of_remarkable_daily_precipitation",
75
+ "Extreme_precipitation_intensity",
76
+ "Mean_winter_temperature",
77
+ "Mean_summer_temperature",
78
+ "Number_of_tropical_nights",
79
+ "Maximum_summer_temperature",
80
+ "Number_of_days_with_Tx_above_30C",
81
+ "Number_of_days_with_Tx_above_35C",
82
+ "Drought_index"
83
+ ]
84
+ prompt = (
85
+ f"You are helping to build a sql query to retrieve relevant data for a user question."
86
+ f"The different tables are {table_names_list}."
87
+ f"The user question is {user_question}. Write the relevant tables to use. Answer only a python list of table name."
88
+ )
89
+ table_names = ast.literal_eval(llm.invoke(prompt).content.strip("```python\n").strip())
90
+ return table_names
91
+
92
+ def replace_coordonates(coords, query, coords_tables):
93
+ n = query.count(str(coords[0]))
94
+
95
+ for i in range(n):
96
+ query = query.replace(str(coords[0]), str(coords_tables[i][0]),1)
97
+ query = query.replace(str(coords[1]), str(coords_tables[i][1]),1)
98
+ return query
climateqa/engine/talk_to_data/vanna_class.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, if relevant. \n"
232
+ "8 Make sure to include the relevant KPI in the SQL query. The query should return impactfull data \n"
233
+ # f"8. If a set of latitude,longitude is provided, make a intermediate query to find the nearest value in the table and replace the coordinates in the sql query. \n"
234
+ # "7. Add a description of the table in the result of the sql query."
235
+ # "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"
236
+ # "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"
237
+ )
238
+
239
+
240
+ message_log = [self.system_message(initial_prompt)]
241
+
242
+ for example in question_sql_list:
243
+ if example is None:
244
+ print("example is None")
245
+ else:
246
+ if example is not None and "question" in example and "sql" in example:
247
+ message_log.append(self.user_message(example["question"]))
248
+ message_log.append(self.assistant_message(example["sql"]))
249
+
250
+ message_log.append(self.user_message(question))
251
+
252
+ return message_log
253
+
254
+
255
+ # def get_sql_prompt(
256
+ # self,
257
+ # initial_prompt : str,
258
+ # question: str,
259
+ # question_sql_list: list,
260
+ # ddl_list: list,
261
+ # doc_list: list,
262
+ # **kwargs,
263
+ # ):
264
+ # """
265
+ # Example:
266
+ # ```python
267
+ # vn.get_sql_prompt(
268
+ # question="What are the top 10 customers by sales?",
269
+ # question_sql_list=[{"question": "What are the top 10 customers by sales?", "sql": "SELECT * FROM customers ORDER BY sales DESC LIMIT 10"}],
270
+ # ddl_list=["CREATE TABLE customers (id INT, name TEXT, sales DECIMAL)"],
271
+ # doc_list=["The customers table contains information about customers and their sales."],
272
+ # )
273
+
274
+ # ```
275
+
276
+ # This method is used to generate a prompt for the LLM to generate SQL.
277
+
278
+ # Args:
279
+ # question (str): The question to generate SQL for.
280
+ # question_sql_list (list): A list of questions and their corresponding SQL statements.
281
+ # ddl_list (list): A list of DDL statements.
282
+ # doc_list (list): A list of documentation.
283
+
284
+ # Returns:
285
+ # any: The prompt for the LLM to generate SQL.
286
+ # """
287
+
288
+ # if initial_prompt is None:
289
+ # initial_prompt = f"You are a {self.dialect} expert. " + \
290
+ # "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. "
291
+
292
+ # initial_prompt = self.add_ddl_to_prompt(
293
+ # initial_prompt, ddl_list, max_tokens=self.max_tokens
294
+ # )
295
+
296
+ # if self.static_documentation != "":
297
+ # doc_list.append(self.static_documentation)
298
+
299
+ # initial_prompt = self.add_documentation_to_prompt(
300
+ # initial_prompt, doc_list, max_tokens=self.max_tokens
301
+ # )
302
+
303
+ # initial_prompt += (
304
+ # "===Response Guidelines \n"
305
+ # "1. If the provided context is sufficient, please generate a valid SQL query without any explanations for the question. \n"
306
+ # "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"
307
+ # "3. If the provided context is insufficient, please explain why it can't be generated. \n"
308
+ # "4. Please use the most relevant table(s). \n"
309
+ # "5. If the question has been asked and answered before, please repeat the answer exactly as it was given before. \n"
310
+ # f"6. Ensure that the output SQL is {self.dialect}-compliant and executable, and free of syntax errors. \n"
311
+ # )
312
+
313
+ # message_log = [self.system_message(initial_prompt)]
314
+
315
+ # for example in question_sql_list:
316
+ # if example is None:
317
+ # print("example is None")
318
+ # else:
319
+ # if example is not None and "question" in example and "sql" in example:
320
+ # message_log.append(self.user_message(example["question"]))
321
+ # message_log.append(self.assistant_message(example["sql"]))
322
+
323
+ # message_log.append(self.user_message(question))
324
+
325
+ # return message_log
front/tabs/chat_interface.py CHANGED
@@ -20,12 +20,31 @@ Please note that we log your questions for meta-analysis purposes, so avoid shar
20
  What do you want to learn ?
21
  """
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
 
25
  # UI Layout Components
26
- def create_chat_interface():
 
27
  chatbot = gr.Chatbot(
28
- value=[ChatMessage(role="assistant", content=init_prompt)],
29
  type="messages",
30
  show_copy_button=True,
31
  show_label=False,
 
20
  What do you want to learn ?
21
  """
22
 
23
+ init_prompt_poc = """
24
+ Hello, I am ClimateQ&A, a conversational assistant designed to help you understand climate change and biodiversity loss. I will answer your questions by **sifting through the IPCC and IPBES scientific reports, PCAET of Paris, the Plan Biodiversité 2018-2024, and Acclimaterra reports from la Région Nouvelle-Aquitaine **.
25
+
26
+ ❓ How to use
27
+ - **Language**: You can ask me your questions in any language.
28
+ - **Audience**: You can specify your audience (children, general public, experts) to get a more adapted answer.
29
+ - **Sources**: You can choose to search in the IPCC or IPBES reports, and POC sources for local documents (PCAET, Plan Biodiversité, Acclimaterra).
30
+ - **Relevant content sources**: You can choose to search for figures, papers, or graphs that can be relevant for your question.
31
+
32
+ ⚠️ Limitations
33
+ *Please note that the AI is not perfect and may sometimes give irrelevant answers. If you are not satisfied with the answer, please ask a more specific question or report your feedback to help us improve the system.*
34
+
35
+ 🛈 Information
36
+ Please note that we log your questions for meta-analysis purposes, so avoid sharing any sensitive or personal information.
37
+
38
+ What do you want to learn ?
39
+ """
40
+
41
 
42
 
43
  # UI Layout Components
44
+ def create_chat_interface(tab):
45
+ init_prompt_message = init_prompt_poc if tab == "Beta - POC Adapt'Action" else init_prompt
46
  chatbot = gr.Chatbot(
47
+ value=[ChatMessage(role="assistant", content=init_prompt_message)],
48
  type="messages",
49
  show_copy_button=True,
50
  show_label=False,
front/tabs/main_tab.py CHANGED
@@ -3,7 +3,6 @@ from .chat_interface import create_chat_interface
3
  from .tab_examples import create_examples_tab
4
  from .tab_papers import create_papers_tab
5
  from .tab_figures import create_figures_tab
6
- from .chat_interface import create_chat_interface
7
 
8
  def cqa_tab(tab_name):
9
  # State variables
@@ -12,7 +11,7 @@ def cqa_tab(tab_name):
12
  with gr.Row(elem_id="chatbot-row"):
13
  # Left column - Chat interface
14
  with gr.Column(scale=2):
15
- chatbot, textbox, config_button = create_chat_interface()
16
 
17
  # Right column - Content panels
18
  with gr.Column(scale=2, variant="panel", elem_id="right-panel"):
 
3
  from .tab_examples import create_examples_tab
4
  from .tab_papers import create_papers_tab
5
  from .tab_figures import create_figures_tab
 
6
 
7
  def cqa_tab(tab_name):
8
  # State variables
 
11
  with gr.Row(elem_id="chatbot-row"):
12
  # Left column - Chat interface
13
  with gr.Column(scale=2):
14
+ chatbot, textbox, config_button = create_chat_interface(tab_name)
15
 
16
  # Right column - Content panels
17
  with gr.Column(scale=2, variant="panel", elem_id="right-panel"):
front/tabs/tab_papers.py CHANGED
@@ -3,6 +3,8 @@ from gradio_modal import Modal
3
 
4
 
5
  def create_papers_tab():
 
 
6
  with gr.Accordion(
7
  visible=True,
8
  elem_id="papers-summary-popup",
@@ -32,5 +34,5 @@ def create_papers_tab():
32
  papers_modal
33
  )
34
 
35
- return papers_summary, papers_html, citations_network, papers_modal
36
 
 
3
 
4
 
5
  def create_papers_tab():
6
+ direct_search_textbox = gr.Textbox(label="Direct search for papers", placeholder= "What is climate change ?", elem_id="papers-search")
7
+
8
  with gr.Accordion(
9
  visible=True,
10
  elem_id="papers-summary-popup",
 
34
  papers_modal
35
  )
36
 
37
+ return direct_search_textbox, papers_summary, papers_html, citations_network, papers_modal
38
 
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
 
sandbox/talk_to_data/20250306 - CQA - Drias.ipynb ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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": null,
13
+ "metadata": {},
14
+ "outputs": [],
15
+ "source": [
16
+ "import sys\n",
17
+ "import os\n",
18
+ "sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))\n",
19
+ "\n",
20
+ "%load_ext autoreload\n",
21
+ "%autoreload 2\n",
22
+ "\n",
23
+ "from climateqa.engine.talk_to_data.main import ask_vanna\n"
24
+ ]
25
+ },
26
+ {
27
+ "cell_type": "markdown",
28
+ "metadata": {},
29
+ "source": [
30
+ "## Create a human query"
31
+ ]
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "execution_count": null,
36
+ "metadata": {},
37
+ "outputs": [],
38
+ "source": [
39
+ "# query = \"Compare the winter and summer precipitation in 2050 in Marseille\"\n",
40
+ "# query = \"What is the impact of climate in Bordeaux?\"\n",
41
+ "# query = \"what is the number of days where the temperature above 35 in 2050 in Marseille\"\n",
42
+ "# query = \"Quelle sera la température à Marseille sur les prochaines années ?\"\n",
43
+ "# query = \"Comment vont évoluer les températures à Marseille ?\"\n",
44
+ "query = \"Comment vont évoluer les températures à marseille ?\""
45
+ ]
46
+ },
47
+ {
48
+ "cell_type": "markdown",
49
+ "metadata": {},
50
+ "source": [
51
+ "## Call the function ask vanna, it gives an output of a the sql query and the dataframe of the result (tuple)"
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "execution_count": null,
57
+ "metadata": {},
58
+ "outputs": [],
59
+ "source": [
60
+ "sql_query, df, fig = ask_vanna(query)\n",
61
+ "print(df.head())\n",
62
+ "fig.show()"
63
+ ]
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "execution_count": null,
68
+ "metadata": {},
69
+ "outputs": [],
70
+ "source": []
71
+ }
72
+ ],
73
+ "metadata": {
74
+ "kernelspec": {
75
+ "display_name": "climateqa",
76
+ "language": "python",
77
+ "name": "python3"
78
+ },
79
+ "language_info": {
80
+ "codemirror_mode": {
81
+ "name": "ipython",
82
+ "version": 3
83
+ },
84
+ "file_extension": ".py",
85
+ "mimetype": "text/x-python",
86
+ "name": "python",
87
+ "nbconvert_exporter": "python",
88
+ "pygments_lexer": "ipython3",
89
+ "version": "3.11.9"
90
+ }
91
+ },
92
+ "nbformat": 4,
93
+ "nbformat_minor": 2
94
+ }
sandbox/talk_to_data/20250306 - CQA - Step_by_step_vanna.ipynb ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": null,
6
+ "metadata": {},
7
+ "outputs": [],
8
+ "source": [
9
+ "import sys\n",
10
+ "import os\n",
11
+ "sys.path.append(os.path.dirname(os.path.dirname(os.getcwd())))\n",
12
+ "\n",
13
+ "%load_ext autoreload\n",
14
+ "%autoreload 2\n",
15
+ "\n",
16
+ "from climateqa.engine.talk_to_data.main import ask_vanna\n",
17
+ "\n",
18
+ "import sqlite3\n",
19
+ "import os\n",
20
+ "import pandas as pd"
21
+ ]
22
+ },
23
+ {
24
+ "cell_type": "markdown",
25
+ "metadata": {},
26
+ "source": [
27
+ "# Imports"
28
+ ]
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "execution_count": null,
33
+ "metadata": {},
34
+ "outputs": [],
35
+ "source": [
36
+ "from climateqa.engine.talk_to_data.myVanna import MyVanna\n",
37
+ "from climateqa.engine.talk_to_data.utils import loc2coords, detect_location_with_openai, detectTable, nearestNeighbourSQL, detect_relevant_tables, replace_coordonates\n",
38
+ "\n",
39
+ "from climateqa.engine.llm import get_llm"
40
+ ]
41
+ },
42
+ {
43
+ "cell_type": "markdown",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Vanna Ask\n"
47
+ ]
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "execution_count": null,
52
+ "metadata": {},
53
+ "outputs": [],
54
+ "source": [
55
+ "from dotenv import load_dotenv\n",
56
+ "\n",
57
+ "load_dotenv()\n",
58
+ "\n",
59
+ "llm = get_llm(provider=\"openai\")\n",
60
+ "\n",
61
+ "OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')\n",
62
+ "PC_API_KEY = os.getenv('VANNA_PINECONE_API_KEY')\n",
63
+ "INDEX_NAME = os.getenv('VANNA_INDEX_NAME')\n",
64
+ "VANNA_MODEL = os.getenv('VANNA_MODEL')\n",
65
+ "\n",
66
+ "ROOT_PATH = os.path.dirname(os.path.dirname(os.getcwd()))\n",
67
+ "\n",
68
+ "#Vanna object\n",
69
+ "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})\n",
70
+ "db_vanna_path = ROOT_PATH + \"/data/drias/drias.db\"\n",
71
+ "vn.connect_to_sqlite(db_vanna_path)\n"
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "markdown",
76
+ "metadata": {},
77
+ "source": [
78
+ "# User query"
79
+ ]
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "execution_count": null,
84
+ "metadata": {},
85
+ "outputs": [],
86
+ "source": [
87
+ "# query = \"Quelle sera la température à Marseille sur les prochaines années ?\"\n",
88
+ "query = \"Comment vont évoluer les températures à marseille ?\""
89
+ ]
90
+ },
91
+ {
92
+ "cell_type": "markdown",
93
+ "metadata": {},
94
+ "source": [
95
+ "## Detect location"
96
+ ]
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "execution_count": null,
101
+ "metadata": {},
102
+ "outputs": [],
103
+ "source": [
104
+ "location = detect_location_with_openai(OPENAI_API_KEY, query)\n",
105
+ "print(location)"
106
+ ]
107
+ },
108
+ {
109
+ "cell_type": "markdown",
110
+ "metadata": {},
111
+ "source": [
112
+ "## Convert location to longitude, latitude coordonate"
113
+ ]
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "execution_count": null,
118
+ "metadata": {},
119
+ "outputs": [],
120
+ "source": [
121
+ "coords = loc2coords(location)\n",
122
+ "user_input = query.lower().replace(location.lower(), f\"lat, long : {coords}\")\n",
123
+ "print(user_input)"
124
+ ]
125
+ },
126
+ {
127
+ "cell_type": "markdown",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Find closest coordonates and replace lat,lon\n"
131
+ ]
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "execution_count": null,
136
+ "metadata": {},
137
+ "outputs": [],
138
+ "source": [
139
+ "relevant_tables = detect_relevant_tables(user_input, llm) \n",
140
+ "coords_tables = [nearestNeighbourSQL(db_vanna_path, coords, relevant_tables[i]) for i in range(len(relevant_tables))]\n",
141
+ "user_input_with_coords = replace_coordonates(coords, user_input, coords_tables)\n",
142
+ "print(user_input_with_coords)"
143
+ ]
144
+ },
145
+ {
146
+ "cell_type": "markdown",
147
+ "metadata": {},
148
+ "source": [
149
+ "# Ask Vanna with correct coordonates"
150
+ ]
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "execution_count": null,
155
+ "metadata": {},
156
+ "outputs": [],
157
+ "source": [
158
+ "sql_query, result_dataframe, figure = vn.ask(user_input_with_coords, print_results=False, allow_llm_to_see_data=True, auto_train=False)\n"
159
+ ]
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "execution_count": null,
164
+ "metadata": {},
165
+ "outputs": [],
166
+ "source": [
167
+ "result_dataframe"
168
+ ]
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "execution_count": null,
173
+ "metadata": {},
174
+ "outputs": [],
175
+ "source": [
176
+ "figure"
177
+ ]
178
+ }
179
+ ],
180
+ "metadata": {
181
+ "kernelspec": {
182
+ "display_name": "climateqa",
183
+ "language": "python",
184
+ "name": "python3"
185
+ },
186
+ "language_info": {
187
+ "codemirror_mode": {
188
+ "name": "ipython",
189
+ "version": 3
190
+ },
191
+ "file_extension": ".py",
192
+ "mimetype": "text/x-python",
193
+ "name": "python",
194
+ "nbconvert_exporter": "python",
195
+ "pygments_lexer": "ipython3",
196
+ "version": "3.11.9"
197
+ }
198
+ },
199
+ "nbformat": 4,
200
+ "nbformat_minor": 2
201
+ }
style.css CHANGED
@@ -481,14 +481,13 @@ a {
481
  max-height: calc(100vh - 190px) !important;
482
  overflow: hidden;
483
  }
484
-
485
  div#tab-examples,
486
  div#sources-textbox,
487
  div#tab-config {
488
  height: calc(100vh - 190px) !important;
489
  overflow-y: scroll !important;
490
  }
491
-
492
  div#sources-figures,
493
  div#graphs-container,
494
  div#tab-citations {
@@ -606,3 +605,16 @@ a {
606
  #checkbox-config:checked {
607
  display: block;
608
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
481
  max-height: calc(100vh - 190px) !important;
482
  overflow: hidden;
483
  }
 
484
  div#tab-examples,
485
  div#sources-textbox,
486
  div#tab-config {
487
  height: calc(100vh - 190px) !important;
488
  overflow-y: scroll !important;
489
  }
490
+ div#tab-vanna,
491
  div#sources-figures,
492
  div#graphs-container,
493
  div#tab-citations {
 
605
  #checkbox-config:checked {
606
  display: block;
607
  }
608
+
609
+ #vanna-display {
610
+ max-height: 300px;
611
+ /* overflow-y: scroll; */
612
+ }
613
+ #sql-query{
614
+ max-height: 100px;
615
+ overflow-y:scroll;
616
+ }
617
+ #vanna-details{
618
+ max-height: 500px;
619
+ overflow-y:scroll;
620
+ }