Merged in dev (pull request #2)
Browse files- .gitignore +6 -1
- app.py +39 -11
- climateqa/chat.py +18 -2
- climateqa/engine/chains/drias_retriever.py +16 -0
- climateqa/engine/chains/intent_categorization.py +2 -1
- climateqa/engine/chains/prompts.py +4 -3
- climateqa/engine/chains/query_transformation.py +2 -0
- climateqa/engine/chains/retrieve_documents.py +48 -14
- climateqa/engine/graph.py +14 -29
- climateqa/engine/talk_to_data/main.py +60 -0
- climateqa/engine/talk_to_data/myVanna.py +13 -0
- climateqa/engine/talk_to_data/utils.py +98 -0
- climateqa/engine/talk_to_data/vanna_class.py +325 -0
- front/tabs/chat_interface.py +21 -2
- front/tabs/main_tab.py +1 -2
- front/tabs/tab_papers.py +3 -1
- requirements.txt +2 -0
- sandbox/20241104 - CQA - StepByStep CQA.ipynb +0 -0
- sandbox/talk_to_data/20250306 - CQA - Drias.ipynb +94 -0
- sandbox/talk_to_data/20250306 - CQA - Step_by_step_vanna.ipynb +201 -0
- style.css +14 -2
.gitignore
CHANGED
@@ -12,4 +12,9 @@ notebooks/
|
|
12 |
data/
|
13 |
sandbox/
|
14 |
|
15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
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,9 +69,9 @@ 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 |
-
if os.
|
71 |
reranker = get_reranker("nano")
|
72 |
-
else:
|
73 |
reranker = get_reranker("large")
|
74 |
|
75 |
agent = make_graph_agent(llm=llm, vectorstore_ipcc=vectorstore, vectorstore_graphs=vectorstore_graphs, vectorstore_region = vectorstore_region, reranker=reranker, threshold_docs=0.2)
|
@@ -94,7 +96,7 @@ async def chat_poc(query, history, audience, sources, reports, relevant_content_
|
|
94 |
# Function to update modal visibility
|
95 |
def update_config_modal_visibility(config_open):
|
96 |
new_config_visibility_status = not config_open
|
97 |
-
return
|
98 |
|
99 |
|
100 |
def update_sources_number_display(sources_textbox, figures_cards, current_graphs, papers_html):
|
@@ -119,7 +121,7 @@ def cqa_tab(tab_name):
|
|
119 |
with gr.Row(elem_id="chatbot-row"):
|
120 |
# Left column - Chat interface
|
121 |
with gr.Column(scale=2):
|
122 |
-
chatbot, textbox, config_button = create_chat_interface()
|
123 |
|
124 |
# Right column - Content panels
|
125 |
with gr.Column(scale=2, variant="panel", elem_id="right-panel"):
|
@@ -142,7 +144,7 @@ def cqa_tab(tab_name):
|
|
142 |
|
143 |
# Papers subtab
|
144 |
with gr.Tab("Papers", elem_id="tab-citations", id=4) as tab_papers:
|
145 |
-
papers_summary, papers_html, citations_network, papers_modal = create_papers_tab()
|
146 |
|
147 |
# Graphs subtab
|
148 |
with gr.Tab("Graphs", elem_id="tab-graphs", id=5) as tab_graphs:
|
@@ -150,6 +152,20 @@ def cqa_tab(tab_name):
|
|
150 |
"<h2>There are no graphs to be displayed at the moment. Try asking another question.</h2>",
|
151 |
elem_id="graphs-container"
|
152 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
153 |
return {
|
154 |
"chatbot": chatbot,
|
155 |
"textbox": textbox,
|
@@ -162,6 +178,7 @@ def cqa_tab(tab_name):
|
|
162 |
"figures_cards": figures_cards,
|
163 |
"gallery_component": gallery_component,
|
164 |
"config_button": config_button,
|
|
|
165 |
"papers_html": papers_html,
|
166 |
"citations_network": citations_network,
|
167 |
"papers_summary": papers_summary,
|
@@ -170,7 +187,10 @@ def cqa_tab(tab_name):
|
|
170 |
"tab_figures": tab_figures,
|
171 |
"tab_graphs": tab_graphs,
|
172 |
"tab_papers": tab_papers,
|
173 |
-
"graph_container": graphs_container
|
|
|
|
|
|
|
174 |
}
|
175 |
|
176 |
|
@@ -191,6 +211,7 @@ def event_handling(
|
|
191 |
figures_cards = main_tab_components["figures_cards"]
|
192 |
gallery_component = main_tab_components["gallery_component"]
|
193 |
config_button = main_tab_components["config_button"]
|
|
|
194 |
papers_html = main_tab_components["papers_html"]
|
195 |
citations_network = main_tab_components["citations_network"]
|
196 |
papers_summary = main_tab_components["papers_summary"]
|
@@ -200,6 +221,10 @@ def event_handling(
|
|
200 |
tab_graphs = main_tab_components["tab_graphs"]
|
201 |
tab_papers = main_tab_components["tab_papers"]
|
202 |
graphs_container = main_tab_components["graph_container"]
|
|
|
|
|
|
|
|
|
203 |
|
204 |
config_open = config_components["config_open"]
|
205 |
config_modal = config_components["config_modal"]
|
@@ -214,8 +239,8 @@ def event_handling(
|
|
214 |
close_config_modal = config_components["close_config_modal_button"]
|
215 |
|
216 |
new_sources_hmtl = gr.State([])
|
217 |
-
|
218 |
-
|
219 |
|
220 |
for button in [config_button, close_config_modal]:
|
221 |
button.click(
|
@@ -265,11 +290,14 @@ def event_handling(
|
|
265 |
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])
|
266 |
|
267 |
# Search for papers
|
268 |
-
for component in [textbox, examples_hidden]:
|
269 |
component.submit(find_papers, [component, after, dropdown_external_sources], [papers_html, citations_network, papers_summary])
|
270 |
-
|
271 |
|
272 |
|
|
|
|
|
|
|
273 |
|
274 |
def main_ui():
|
275 |
# config_open = gr.State(True)
|
@@ -283,7 +311,7 @@ def main_ui():
|
|
283 |
create_about_tab()
|
284 |
|
285 |
event_handling(cqa_components, config_components, tab_name = 'ClimateQ&A')
|
286 |
-
event_handling(local_cqa_components, config_components, tab_name =
|
287 |
|
288 |
demo.queue()
|
289 |
|
|
|
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)
|
|
|
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,
|
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
|
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.
|
|
|
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.
|
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
@@ -369,22 +369,38 @@ async def retrieve_documents(
|
|
369 |
return docs_question, images_question
|
370 |
|
371 |
|
372 |
-
async def retrieve_documents_for_all_questions(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
373 |
"""
|
374 |
Retrieve documents in parallel for all questions.
|
375 |
"""
|
376 |
# to_handle_questions_index = [x for x in state["questions_list"] if x["source_type"] == "IPx"]
|
377 |
|
378 |
# 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
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
reports = state["reports"]
|
384 |
|
385 |
-
k_by_question = k_final // state["n_questions"]["total"]
|
386 |
-
k_summary_by_question = _get_k_summary_by_question(state["n_questions"]["total"])
|
387 |
-
k_images_by_question = _get_k_images_by_question(state["n_questions"]["total"])
|
|
|
|
|
|
|
388 |
k_before_reranking=100
|
389 |
|
390 |
tasks = [
|
@@ -403,7 +419,7 @@ async def retrieve_documents_for_all_questions(state, config, source_type, to_ha
|
|
403 |
k_by_question=k_by_question,
|
404 |
k_summary_by_question=k_summary_by_question
|
405 |
)
|
406 |
-
for i, question in enumerate(
|
407 |
]
|
408 |
results = await asyncio.gather(*tasks)
|
409 |
# Combine results
|
@@ -419,10 +435,18 @@ def make_IPx_retriever_node(vectorstore,reranker,llm,rerank_by_question=True, k_
|
|
419 |
source_type = "IPx"
|
420 |
IPx_questions_index = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "IPx"]
|
421 |
|
422 |
-
|
423 |
-
|
|
|
|
|
|
|
|
|
424 |
state = await retrieve_documents_for_all_questions(
|
425 |
-
|
|
|
|
|
|
|
|
|
426 |
config=config,
|
427 |
source_type=source_type,
|
428 |
to_handle_questions_index=IPx_questions_index,
|
@@ -446,8 +470,18 @@ def make_POC_retriever_node(vectorstore,reranker,llm,rerank_by_question=True, k_
|
|
446 |
source_type = "POC"
|
447 |
POC_questions_index = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "POC"]
|
448 |
|
|
|
|
|
|
|
|
|
|
|
|
|
449 |
state = await retrieve_documents_for_all_questions(
|
450 |
-
|
|
|
|
|
|
|
|
|
451 |
config=config,
|
452 |
source_type=source_type,
|
453 |
to_handle_questions_index=POC_questions_index,
|
|
|
369 |
return docs_question, images_question
|
370 |
|
371 |
|
372 |
+
async def retrieve_documents_for_all_questions(
|
373 |
+
search_figures,
|
374 |
+
search_only,
|
375 |
+
reports,
|
376 |
+
questions_list,
|
377 |
+
n_questions,
|
378 |
+
config,
|
379 |
+
source_type,
|
380 |
+
to_handle_questions_index,
|
381 |
+
vectorstore,
|
382 |
+
reranker,
|
383 |
+
rerank_by_question=True,
|
384 |
+
k_final=15,
|
385 |
+
k_before_reranking=100
|
386 |
+
):
|
387 |
"""
|
388 |
Retrieve documents in parallel for all questions.
|
389 |
"""
|
390 |
# to_handle_questions_index = [x for x in state["questions_list"] if x["source_type"] == "IPx"]
|
391 |
|
392 |
# 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
|
393 |
+
# search_figures = "Figures (IPCC/IPBES)" in state["relevant_content_sources_selection"]
|
394 |
+
# search_only = state["search_only"]
|
395 |
+
# reports = state["reports"]
|
396 |
+
# questions_list = state["questions_list"]
|
|
|
397 |
|
398 |
+
# k_by_question = k_final // state["n_questions"]["total"]
|
399 |
+
# k_summary_by_question = _get_k_summary_by_question(state["n_questions"]["total"])
|
400 |
+
# k_images_by_question = _get_k_images_by_question(state["n_questions"]["total"])
|
401 |
+
k_by_question = k_final // n_questions
|
402 |
+
k_summary_by_question = _get_k_summary_by_question(n_questions)
|
403 |
+
k_images_by_question = _get_k_images_by_question(n_questions)
|
404 |
k_before_reranking=100
|
405 |
|
406 |
tasks = [
|
|
|
419 |
k_by_question=k_by_question,
|
420 |
k_summary_by_question=k_summary_by_question
|
421 |
)
|
422 |
+
for i, question in enumerate(questions_list) if i in to_handle_questions_index
|
423 |
]
|
424 |
results = await asyncio.gather(*tasks)
|
425 |
# Combine results
|
|
|
435 |
source_type = "IPx"
|
436 |
IPx_questions_index = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "IPx"]
|
437 |
|
438 |
+
search_figures = "Figures (IPCC/IPBES)" in state["relevant_content_sources_selection"]
|
439 |
+
search_only = state["search_only"]
|
440 |
+
reports = state["reports"]
|
441 |
+
questions_list = state["questions_list"]
|
442 |
+
n_questions=state["n_questions"]["total"]
|
443 |
+
|
444 |
state = await retrieve_documents_for_all_questions(
|
445 |
+
search_figures=search_figures,
|
446 |
+
search_only=search_only,
|
447 |
+
reports=reports,
|
448 |
+
questions_list=questions_list,
|
449 |
+
n_questions=n_questions,
|
450 |
config=config,
|
451 |
source_type=source_type,
|
452 |
to_handle_questions_index=IPx_questions_index,
|
|
|
470 |
source_type = "POC"
|
471 |
POC_questions_index = [i for i, x in enumerate(state["questions_list"]) if x["source_type"] == "POC"]
|
472 |
|
473 |
+
search_figures = "Figures (IPCC/IPBES)" in state["relevant_content_sources_selection"]
|
474 |
+
search_only = state["search_only"]
|
475 |
+
reports = state["reports"]
|
476 |
+
questions_list = state["questions_list"]
|
477 |
+
n_questions=state["n_questions"]["total"]
|
478 |
+
|
479 |
state = await retrieve_documents_for_all_questions(
|
480 |
+
search_figures=search_figures,
|
481 |
+
search_only=search_only,
|
482 |
+
reports=reports,
|
483 |
+
questions_list=questions_list,
|
484 |
+
n_questions=n_questions,
|
485 |
config=config,
|
486 |
source_type=source_type,
|
487 |
to_handle_questions_index=POC_questions_index,
|
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
|
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=
|
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 |
+
}
|