Nelly-43 commited on
Commit
6c1a39c
Β·
verified Β·
1 Parent(s): f66245a

Update app_web.py

Browse files
Files changed (1) hide show
  1. app_web.py +102 -25
app_web.py CHANGED
@@ -1,26 +1,20 @@
1
  """Streamlit web UI for the RAG Research Chatbot."""
2
  import os
3
- import time
4
  import streamlit as st
5
- from streamlit_javascript import st_javascript
6
 
7
  from src.config_loader import load_config, get_api_key
8
  from src.ingest import get_chroma_collection, ingest_documents
9
  from src.kb_meta import load_kb_meta_brief
10
- from src.query_engine import understand_query
11
  from src.retriever import clear_collection_cache, retrieve
12
  from src.verifier import verify_and_respond
13
  from src.llm import list_models
14
- from huggingface_hub import snapshot_download, whoami
15
 
16
- snapshot_download(repo_id="CGIAR/weai-kb",
17
- repo_type="dataset",
18
- token=os.getenv('HF_TOKEN'),
19
- local_dir="./"
20
- )
21
- # 1. Define the asynchronous JavaScript logic to request user plans
22
 
23
  # ── Session initialisation ───────────────────────────────────────────────────
 
24
  def init_session():
25
  """Initialise st.session_state with messages list, cfg, and last_retrieval."""
26
  if "messages" not in st.session_state:
@@ -49,23 +43,23 @@ def render_sidebar():
49
 
50
  with st.sidebar:
51
  st.header("Settings")
52
-
53
  # --- Provider dropdown ---
54
  providers = ["openai", "anthropic", "gemini", "meta-llama"]
55
  current_provider = cfg.get("llm", {}).get("provider", "openai")
56
  provider_index = providers.index(current_provider) if current_provider in providers else 0
57
-
58
  provider = st.selectbox(
59
  "LLM Provider",
60
  providers,
61
  index=provider_index,
62
  key="sidebar_provider",
63
  )
64
-
65
  # Update cfg in session when provider changes
66
  if provider != cfg.get("llm", {}).get("provider"):
67
  cfg.setdefault("llm", {})["provider"] = provider
68
-
69
  # --- Model dropdown (cached per provider) ---
70
  # Invalidate model cache if provider changed
71
  prev_provider_key = "prev_provider"
@@ -73,7 +67,7 @@ def render_sidebar():
73
  for p in providers:
74
  st.session_state.pop(f"models_{p}", None)
75
  st.session_state[prev_provider_key] = provider
76
-
77
  models_cache_key = f"models_{provider}"
78
  if models_cache_key not in st.session_state:
79
  api_key = get_api_key(cfg, provider)
@@ -84,10 +78,10 @@ def render_sidebar():
84
  st.session_state[models_cache_key] = []
85
  else:
86
  st.session_state[models_cache_key] = []
87
-
88
  available_models = st.session_state[models_cache_key]
89
  current_model = cfg.get("llm", {}).get("model", "")
90
-
91
  if available_models:
92
  model_index = (
93
  available_models.index(current_model)
@@ -106,18 +100,18 @@ def render_sidebar():
106
  value=current_model,
107
  key="sidebar_model_text",
108
  )
109
-
110
  # Update cfg in session when model changes
111
  if model != cfg.get("llm", {}).get("model"):
112
  cfg.setdefault("llm", {})["model"] = model
113
-
114
  # --- Web search toggle ---
115
  web_enabled = cfg.get("web_search", {}).get("enabled", False)
116
  web_toggle = st.toggle("Web search", value=web_enabled, key="sidebar_web_search")
117
  cfg.setdefault("web_search", {})["enabled"] = web_toggle
118
-
119
  st.divider()
120
-
121
  # --- Knowledge base stats ---
122
  st.subheader("Knowledge Base")
123
  try:
@@ -127,7 +121,7 @@ def render_sidebar():
127
  except Exception as e:
128
  st.warning(f"Could not read knowledge base: {e}")
129
  chunk_count = 0
130
-
131
  # --- Re-ingest button ---
132
  if st.button("Re-ingest documents", use_container_width=True):
133
  st.info("Ingestion may take a few minutes for large document collections...")
@@ -143,8 +137,6 @@ def render_sidebar():
143
  st.error(f"Ingestion failed: {e}")
144
 
145
 
146
- st.header("Upload Documents")
147
-
148
  # ── Chat interface ───────────────────────────────────────────────────────────
149
 
150
  def render_chat():
@@ -165,6 +157,91 @@ def render_chat():
165
  with st.chat_message("user"):
166
  st.markdown(prompt)
167
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  # ── Check if this is a clarification response ───────────────────
169
  pending = st.session_state.pending_clarification
170
  if pending is not None:
@@ -329,7 +406,7 @@ def main():
329
  if kb_summary:
330
  with st.expander("Knowledge Base Contents", expanded=True):
331
  st.markdown(kb_summary)
332
-
333
  render_sidebar()
334
  render_chat()
335
 
 
1
  """Streamlit web UI for the RAG Research Chatbot."""
2
  import os
3
+ import zipfile
4
  import streamlit as st
 
5
 
6
  from src.config_loader import load_config, get_api_key
7
  from src.ingest import get_chroma_collection, ingest_documents
8
  from src.kb_meta import load_kb_meta_brief
9
+ from src.query_engine import understand_query, categorize_query
10
  from src.retriever import clear_collection_cache, retrieve
11
  from src.verifier import verify_and_respond
12
  from src.llm import list_models
13
+ from src.stata import explain_
14
 
 
 
 
 
 
 
15
 
16
  # ── Session initialisation ───────────────────────────────────────────────────
17
+
18
  def init_session():
19
  """Initialise st.session_state with messages list, cfg, and last_retrieval."""
20
  if "messages" not in st.session_state:
 
43
 
44
  with st.sidebar:
45
  st.header("Settings")
46
+
47
  # --- Provider dropdown ---
48
  providers = ["openai", "anthropic", "gemini", "meta-llama"]
49
  current_provider = cfg.get("llm", {}).get("provider", "openai")
50
  provider_index = providers.index(current_provider) if current_provider in providers else 0
51
+
52
  provider = st.selectbox(
53
  "LLM Provider",
54
  providers,
55
  index=provider_index,
56
  key="sidebar_provider",
57
  )
58
+
59
  # Update cfg in session when provider changes
60
  if provider != cfg.get("llm", {}).get("provider"):
61
  cfg.setdefault("llm", {})["provider"] = provider
62
+
63
  # --- Model dropdown (cached per provider) ---
64
  # Invalidate model cache if provider changed
65
  prev_provider_key = "prev_provider"
 
67
  for p in providers:
68
  st.session_state.pop(f"models_{p}", None)
69
  st.session_state[prev_provider_key] = provider
70
+
71
  models_cache_key = f"models_{provider}"
72
  if models_cache_key not in st.session_state:
73
  api_key = get_api_key(cfg, provider)
 
78
  st.session_state[models_cache_key] = []
79
  else:
80
  st.session_state[models_cache_key] = []
81
+
82
  available_models = st.session_state[models_cache_key]
83
  current_model = cfg.get("llm", {}).get("model", "")
84
+
85
  if available_models:
86
  model_index = (
87
  available_models.index(current_model)
 
100
  value=current_model,
101
  key="sidebar_model_text",
102
  )
103
+
104
  # Update cfg in session when model changes
105
  if model != cfg.get("llm", {}).get("model"):
106
  cfg.setdefault("llm", {})["model"] = model
107
+
108
  # --- Web search toggle ---
109
  web_enabled = cfg.get("web_search", {}).get("enabled", False)
110
  web_toggle = st.toggle("Web search", value=web_enabled, key="sidebar_web_search")
111
  cfg.setdefault("web_search", {})["enabled"] = web_toggle
112
+
113
  st.divider()
114
+
115
  # --- Knowledge base stats ---
116
  st.subheader("Knowledge Base")
117
  try:
 
121
  except Exception as e:
122
  st.warning(f"Could not read knowledge base: {e}")
123
  chunk_count = 0
124
+
125
  # --- Re-ingest button ---
126
  if st.button("Re-ingest documents", use_container_width=True):
127
  st.info("Ingestion may take a few minutes for large document collections...")
 
137
  st.error(f"Ingestion failed: {e}")
138
 
139
 
 
 
140
  # ── Chat interface ───────────────────────────────────────────────────────────
141
 
142
  def render_chat():
 
157
  with st.chat_message("user"):
158
  st.markdown(prompt)
159
 
160
+ # ── Categorize user query ───────────────────
161
+ prompt_cat = categorize_query(prompt, cfg)
162
+ save_dir = "uploaded_do_files"
163
+ os.makedirs(save_dir, exist_ok=True)
164
+
165
+ # Exclude the just-appended user message to avoid sending
166
+ # the current question twice (once in history, once as query)
167
+ cat_cfg = cfg.get("query_categorization", {})
168
+ max_history = cat_cfg.get("max_history", 6)
169
+
170
+ prior_messages = st.session_state.messages[:-1]
171
+ history = [
172
+ {"role": m["role"], "content": m["content"]}
173
+ for m in prior_messages[-max_history:]
174
+ ]
175
+ try:
176
+ qcat_result = categorize_query(combined, cfg, history)
177
+ except Exception:
178
+ qcat_result = {"category": "general", "action": "continue"}
179
+
180
+ if qcat_result.get("category") == "contact_and_info" and qcat_result.get("action") == "contact":
181
+ with st.chat_message("assistant"):
182
+ st.markdown("For additional assistance, please contact the WEAI Helpdesk at IFPRI-WEAI@cgiar.org.\
183
+ Please let me know if there's anything else I can assist you with today.")
184
+ return
185
+ if qcat_result.get("category") == "contact_and_info" and qcat_result.get("action") == "upload":#st.session_state.clarification_rounds < max_clarifications:
186
+
187
+ # Allow multiple file uploads
188
+ uploaded_files = st.file_uploader("Choose files to zip", accept_multiple_files=True)
189
+
190
+ if uploaded_files:
191
+ # Specify the path where the zip file will be saved
192
+ zip_filename = "uploaded_files.zip"
193
+
194
+ # Write uploaded files into a single zip archive on disk
195
+ with zipfile.ZipFile(zip_filename, "w", zipfile.ZIP_DEFLATED) as zipf:
196
+ for file in uploaded_files:
197
+ # Write each file's bytes directly into the zip
198
+ zipf.writestr(file.name, file.getvalue())
199
+
200
+ st.success(f"Successfully uploaded {len(uploaded_files)} files!")
201
+
202
+ with st.chat_message("assistant"):
203
+ st.markdown("Thank you for sharing these resources with us. The WEAI team will work to \
204
+ review the files and reach out to you should we need any more information. \
205
+ Please let me know if there's anything else I can assist you with today.")
206
+ return
207
+
208
+ if qcat_result.get("category") == "stata":
209
+ if qcat_result.get("action") == "do":
210
+ options = {"rewrite do-file":"rewrite",
211
+ "explain the do-file":"explain",
212
+ "suggest fix(es) for any errors in the do-file":"suggestfix"}
213
+ file_path = ""
214
+ # Accept .do files
215
+ uploaded_file = st.file_uploader("Upload a Stata .do file", type=["do"])
216
+
217
+ if uploaded_file is not None:
218
+ # Define the full file path on disk
219
+ file_path = os.path.join(save_dir, uploaded_file.name)
220
+
221
+ # Write the uploaded bytes to the local path
222
+ with open(file_path, "wb") as f:
223
+ f.write(uploaded_file.getbuffer())
224
+
225
+ st.success(f"File successfully uploaded")
226
+
227
+ if qcat_result.get("action") == "code":
228
+ options = {"rewrite the stata code":"rewrite",
229
+ "explain the stata code":"explain",
230
+ "suggest fix(es) for any errors in the code":"suggestfix"}
231
+
232
+ if qcat_result.get("action") == "error":
233
+ options = {"explain the error":"explain",
234
+ "suggest fix(es) for the error":"suggestfix"}
235
+
236
+ selection = st.multiselect("Please let me know what you need help with:", options.keys())
237
+
238
+ opts = [options.get(s) for s in selection]
239
+ result = explain_(qcat_result.get("action"), prompt, cfg, file_path, opts)
240
+
241
+ with st.chat_message("assistant"):
242
+ st.markdown(result)
243
+ return
244
+
245
  # ── Check if this is a clarification response ───────────────────
246
  pending = st.session_state.pending_clarification
247
  if pending is not None:
 
406
  if kb_summary:
407
  with st.expander("Knowledge Base Contents", expanded=True):
408
  st.markdown(kb_summary)
409
+
410
  render_sidebar()
411
  render_chat()
412