broadfield-dev commited on
Commit
b7e81ea
Β·
verified Β·
1 Parent(s): 1682041

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +953 -200
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import os
2
  import json
3
  import re
@@ -12,26 +13,29 @@ import xml.etree.ElementTree as ET
12
  load_dotenv()
13
 
14
  MEMORY_STORAGE_TYPE = "HF_DATASET"
 
 
 
15
  HF_DATASET_MEMORY_REPO = "broadfield-dev/ai-brain"
16
  HF_DATASET_RULES_REPO = "broadfield-dev/ai-rules"
17
 
 
18
  os.environ['STORAGE_BACKEND'] = MEMORY_STORAGE_TYPE
19
  if MEMORY_STORAGE_TYPE == "HF_DATASET":
20
  os.environ['HF_MEMORY_DATASET_REPO'] = HF_DATASET_MEMORY_REPO
21
  os.environ['HF_RULES_DATASET_REPO'] = HF_DATASET_RULES_REPO
 
22
 
23
  from model_logic import (
24
  get_available_providers, get_model_display_names_for_provider,
25
  get_default_model_display_name_for_provider, call_model_stream, MODELS_BY_PROVIDER
26
  )
27
  from memory_logic import (
28
- initialize_memory_system, search_memories, add_memory_entry,
29
- retrieve_rules_semantic, get_all_rules_cached, get_all_memories_cached,
30
- add_rule_entry, remove_rule_entry, clear_all_memory_data_backend, clear_all_rules_data_backend,
31
- save_faiss_indices_to_disk, STORAGE_BACKEND as MEMORY_STORAGE_BACKEND,
32
- SQLITE_DB_PATH as MEMORY_SQLITE_PATH,
33
- HF_MEMORY_DATASET_REPO as MEMORY_HF_MEM_REPO,
34
- HF_RULES_DATASET_REPO as MEMORY_HF_RULES_REPO
35
  )
36
  from websearch_logic import scrape_url, search_and_scrape_duckduckgo, search_and_scrape_google
37
 
@@ -51,11 +55,17 @@ DEFAULT_SYSTEM_PROMPT = os.getenv(
51
  "Your Name is Node. You are a Helpful AI Assistant, and your goal is to improve yourself, so that you can improve everybody elses life. Your job is to answer questions and perform research tasks accurately and thoroughly. You can use tools like web search and page browsing. When providing information from the web, cite your sources if possible. If asked to perform a task beyond your capabilities, explain politely. Be concise unless asked for detail."
52
  )
53
 
 
54
  LOAD_RULES_FILE = os.getenv("LOAD_RULES_FILE")
55
  LOAD_MEMORIES_FILE = os.getenv("LOAD_MEMORIES_FILE")
 
 
56
 
 
 
57
  def format_insights_for_prompt(retrieved_insights_list: list[str]) -> tuple[str, list[dict]]:
58
- if not retrieved_insights_list: return "No specific guiding principles or learned insights retrieved.", []
 
59
  parsed = []
60
  for text in retrieved_insights_list:
61
  match = re.match(r"\[(CORE_RULE|RESPONSE_PRINCIPLE|BEHAVIORAL_ADJUSTMENT|GENERAL_LEARNING)\|([\d\.]+?)\](.*)", text.strip(), re.DOTALL | re.IGNORECASE)
@@ -65,124 +75,144 @@ def format_insights_for_prompt(retrieved_insights_list: list[str]) -> tuple[str,
65
  parsed.append({"type": "GENERAL_LEARNING", "score": "0.5", "text": text.strip(), "original": text.strip()})
66
  try:
67
  parsed.sort(key=lambda x: float(x["score"]) if x["score"].replace('.', '', 1).isdigit() else -1.0, reverse=True)
68
- except ValueError: pass
69
  grouped = {"CORE_RULE": [], "RESPONSE_PRINCIPLE": [], "BEHAVIORAL_ADJUSTMENT": [], "GENERAL_LEARNING": []}
70
  for p_item in parsed: grouped.get(p_item["type"], grouped["GENERAL_LEARNING"]).append(f"- (Score: {p_item['score']}) {p_item['text']}")
71
  sections = [f"{k.replace('_', ' ').title()}:\n" + "\n".join(v) for k, v in grouped.items() if v]
72
  return "\n\n".join(sections) if sections else "No guiding principles retrieved.", parsed
73
 
74
  def generate_interaction_metrics(user_input: str, bot_response: str, provider: str, model_display_name: str, api_key_override: str = None) -> dict:
75
- metric_messages = [
76
- {"role": "system", "content": "You are a precise JSON output agent. Output a single JSON object containing interaction metrics as requested. Do not include any explanatory text."},
77
- {"role": "user", "content": f"User: \"{user_input}\"\nAI: \"{bot_response}\"\nMetrics: \"takeaway\" (3-7 words), \"response_success_score\" (0.0-1.0), \"future_confidence_score\" (0.0-1.0). Output JSON ONLY."}
78
- ]
79
  try:
 
80
  metrics_model_env = os.getenv("METRICS_MODEL")
81
  if metrics_model_env and "/" in metrics_model_env:
82
  m_prov, m_id = metrics_model_env.split('/', 1)
83
  m_disp_name = next((dn for dn, mid in MODELS_BY_PROVIDER.get(m_prov.lower(), {}).get("models", {}).items() if mid == m_id), None)
84
- if m_disp_name: provider, model_display_name = m_prov, m_disp_name
85
-
86
- resp_str = "".join(list(call_model_stream(provider=provider, model_display_name=model_display_name, messages=metric_messages, api_key_override=api_key_override, temperature=0.05, max_tokens=200)))
87
- json_match = re.search(r"\{.*\}", resp_str, re.DOTALL)
88
- if json_match:
89
- metrics_data = json.loads(json_match.group(0))
90
- return {"takeaway": metrics_data.get("takeaway", "N/A"), "response_success_score": float(metrics_data.get("response_success_score", 0.5)), "future_confidence_score": float(metrics_data.get("future_confidence_score", 0.5))}
 
 
 
 
 
91
  except Exception as e:
92
- logger.error(f"METRICS_GEN Error: {e}")
93
- return {"takeaway": "N/A", "response_success_score": 0.5, "future_confidence_score": 0.5, "error": "metrics format error"}
 
94
 
95
  def process_user_interaction_gradio(user_input: str, provider_name: str, model_display_name: str, chat_history_for_prompt: list[dict], custom_system_prompt: str = None, ui_api_key_override: str = None):
 
96
  request_id = os.urandom(4).hex()
97
- logger.info(f"PUI_GRADIO [{request_id}] Start. User: '{user_input[:50]}...'")
98
  history_str_for_prompt = "\n".join([f"{('User' if t_msg['role'] == 'user' else 'AI')}: {t_msg['content']}" for t_msg in chat_history_for_prompt[-(MAX_HISTORY_TURNS * 2):]])
99
- yield "status", "<i>[Checking guidelines...]</i>"
100
- initial_insights, parsed_initial_insights_list = format_insights_for_prompt(retrieve_rules_semantic(f"{user_input}\n{history_str_for_prompt}", k=5))
101
-
102
- action_type = "quick_respond"
103
- action_input_dict = {}
104
-
105
- if not (len(user_input.split()) <= 3 and any(kw in user_input.lower() for kw in ["hello", "hi", "thanks", "ok", "bye"]) and "?" not in user_input):
 
 
 
 
 
106
  yield "status", "<i>[LLM choosing best approach...]</i>"
107
- tool_definitions = {
108
- "answer_using_conversation_memory": "Use if the user's query refers to a past conversation, asks you to 'remember' or 'recall' something, or seems to require knowledge you might have gained previously.",
109
- "search_duckduckgo_and_report": "Use for general knowledge questions, current events, or explicit requests to search the web.",
110
- "quick_respond": "Use as a fallback for simple greetings or if the answer is obvious from immediate context."
111
- }
112
- available_tools = ["quick_respond", "answer_using_conversation_memory"] + (["search_duckduckgo_and_report"] if WEB_SEARCH_ENABLED else [])
113
- tool_desc = "\n".join(f'- "{name}": {tool_definitions[name]}' for name in available_tools)
114
- tool_sys_prompt = "You are a precise routing agent. Analyze the user's query and select the single best action. Output ONLY a valid JSON object like {\"action\": \"action_name\", \"action_input\": {\"param\": \"value\"}}."
115
- tool_user_prompt = f"User Query: \"{user_input}\"\n\nAvailable Actions:\n{tool_desc}\n\nSelect one action."
116
-
117
  tool_provider, tool_model_id = TOOL_DECISION_PROVIDER_ENV, TOOL_DECISION_MODEL_ID_ENV
118
  tool_model_display = next((dn for dn, mid in MODELS_BY_PROVIDER.get(tool_provider.lower(), {}).get("models", {}).items() if mid == tool_model_id), None)
119
  if not tool_model_display: tool_model_display = get_default_model_display_name_for_provider(tool_provider)
120
-
121
- try:
122
- tool_resp_raw = "".join(list(call_model_stream(provider=tool_provider, model_display_name=tool_model_display, messages=[{"role":"system", "content": tool_sys_prompt}, {"role":"user", "content": tool_user_prompt}], temperature=0.0, max_tokens=150)))
123
- json_match_tool = re.search(r"\{.*\}", tool_resp_raw, re.DOTALL)
124
- if json_match_tool:
125
- action_data = json.loads(json_match_tool.group(0))
126
- action_type = action_data.get("action", "quick_respond")
127
- action_input_dict = action_data.get("action_input", {})
128
- except Exception as e:
129
- logger.error(f"Tool decision error: {e}")
130
- action_type = "quick_respond"
131
-
 
 
 
 
 
132
  yield "status", f"<i>[Path: {action_type}. Preparing response...]</i>"
133
- final_system_prompt_str = custom_system_prompt or DEFAULT_SYSTEM_PROMPT
134
-
135
- if action_type == "answer_using_conversation_memory":
136
- yield "status", "<i>[Optimizing query for memory search...]</i>"
137
- optimized_query = user_input
138
- try:
139
- query_gen_sys = "Reformulate the user's question into a concise, self-contained search query for a vector database. Output ONLY the query text."
140
- query_gen_user = f"History:\n{history_str_for_prompt}\n\nUser Query: \"{user_input}\"\n\nOptimized Query:"
141
- generated_query = "".join(list(call_model_stream(provider=tool_provider, model_display_name=tool_model_display, messages=[{"role":"system", "content":query_gen_sys}, {"role":"user", "content":query_gen_user}], temperature=0.0, max_tokens=50))).strip().replace('"', '')
142
- if generated_query: optimized_query = generated_query
143
- except Exception: pass
144
- logger.info(f"Optimized memory search query: '{optimized_query}'")
145
-
146
- yield "status", "<i>[Searching memories...]</i>"
147
- retrieved_mems, search_path = search_memories(query=optimized_query, k=3, threshold=1.0)
148
-
149
- if search_path == "deep":
150
- yield "status", "<i>[No recent match. Performing deep search...]</i>"
151
-
152
- memory_context = "No relevant past interactions found."
153
- if retrieved_mems:
154
- memory_context = "Relevant Past Interactions:\n" + "\n".join([f"- User asked: '{m.get('user_input','')}'. You responded: '{m.get('bot_response','')}'. (Takeaway: {m.get('metrics',{}).get('takeaway','N/A')})" for m in retrieved_mems])
155
-
156
- final_system_prompt_str += " You MUST use the 'Memory Context' to inform your answer."
157
- final_user_prompt_content_str = f"History:\n{history_str_for_prompt}\n\nGuidelines:\n{initial_insights}\n\nMemory Context:\n{memory_context}\n\nUser Query: \"{user_input}\"\n\nResponse:"
158
- elif action_type == "search_duckduckgo_and_report":
159
- query_or_url = action_input_dict.get("search_engine_query", user_input)
160
- yield "status", f"<i>[Web: '{query_or_url[:60]}'...]</i>"
161
- web_results = search_and_scrape_duckduckgo(query_or_url, num_results=2)
162
- scraped_content = "\n".join([f"Source {i+1}:\nURL:{r.get('url','N/A')}\nTitle:{r.get('title','N/A')}\nContent:\n{(r.get('content') or r.get('error') or 'N/A')[:3500]}\n---" for i,r in enumerate(web_results)]) if web_results else f"No results for '{query_or_url}'."
163
- yield "status", "<i>[Synthesizing web report...]</i>"
164
- final_system_prompt_str += " Generate a report from web content, citing URLs as [Source X]."
165
- final_user_prompt_content_str = f"History:\n{history_str_for_prompt}\nGuidelines:\n{initial_insights}\nWeb Content:\n{scraped_content}\nQuery: \"{user_input}\"\nReport/Response:"
166
  else:
167
- final_user_prompt_content_str = f"History:\n{history_str_for_prompt}\nGuidelines:\n{initial_insights}\nQuery: \"{user_input}\"\nResponse:"
168
-
169
  final_llm_messages = [{"role": "system", "content": final_system_prompt_str}, {"role": "user", "content": final_user_prompt_content_str}]
170
- streamed_response = ""
171
- for chunk in call_model_stream(provider=provider_name, model_display_name=model_display_name, messages=final_llm_messages, api_key_override=ui_api_key_override, temperature=0.6, max_tokens=2500):
172
- streamed_response += chunk
173
- yield "response_chunk", chunk
174
-
175
- final_bot_text = streamed_response.strip() or "(No response.)"
 
 
 
 
 
176
  yield "final_response_and_insights", {"response": final_bot_text, "insights_used": parsed_initial_insights_list}
177
 
178
  def perform_post_interaction_learning(user_input: str, bot_response: str, provider: str, model_disp_name: str, insights_reflected: list[dict], api_key_override: str = None):
179
  task_id = os.urandom(4).hex()
180
- logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: START")
181
- metrics = generate_interaction_metrics(user_input, bot_response, provider, model_disp_name, api_key_override)
182
- add_memory_entry(user_input, metrics, bot_response)
183
- summary = f"User:\"{user_input}\"\nAI:\"{bot_response}\"\nMetrics(takeaway):{metrics.get('takeaway','N/A')},Success:{metrics.get('response_success_score','N/A')}"
184
- existing_rules_ctx = "\n".join([f"- \"{r}\"" for r in retrieve_rules_semantic(f"{summary}\n{user_input}", k=10)]) or "No existing rules context."
185
- insight_sys_prompt = """You are an expert AI knowledge base curator. Your primary function is to meticulously analyze an interaction and update the AI's guiding principles (insights/rules) to improve its future performance and self-understanding.
 
 
 
 
 
 
 
186
  **CRITICAL OUTPUT REQUIREMENT: You MUST output a single, valid XML structure representing a list of operation objects.**
187
  The root element should be `<operations_list>`. Each operation should be an `<operation>` element.
188
  If no operations are warranted, output an empty list: `<operations_list></operations_list>`.
@@ -191,63 +221,181 @@ Each `<operation>` element must contain the following child elements:
191
  1. `<action>`: A string, either `"add"` (for entirely new rules) or `"update"` (to replace an existing rule with a better one).
192
  2. `<insight>`: The full, refined insight text including its `[TYPE|SCORE]` prefix (e.g., `[CORE_RULE|1.0] My name is Lumina, an AI assistant.`). Multi-line insight text can be placed directly within this tag; XML handles newlines naturally.
193
  3. `<old_insight_to_replace>`: (ONLY for `"update"` action) The *exact, full text* of an existing insight that the new `<insight>` should replace. If action is `"add"`, this element should be omitted or empty.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
194
  """
195
- insight_user_prompt = f"""Interaction Summary:\n{summary}\n
196
  Potentially Relevant Existing Rules (Review these carefully. Your main goal is to consolidate CORE_RULEs and then identify other changes/additions based on the Interaction Summary and these existing rules):\n{existing_rules_ctx}\n
197
  Guiding principles that were considered during THIS interaction (these might offer clues for new rules or refinements):\n{json.dumps([p['original'] for p in insights_reflected if 'original' in p]) if insights_reflected else "None"}\n
198
- Task: Based on your reflection process:
199
- 1. **Consolidate CORE_RULEs:** Merge similar identity/purpose rules into single, definitive statements using "update" operations.
200
- 2. **Add New Learnings:** "add" any distinct new facts, skills, or important user preferences learned from the "Interaction Summary".
201
- 3. **Update Existing Principles:** "update" any non-core principles if the "Interaction Summary" provided a clear refinement.
202
- Combine all findings into a single, valid XML structure. Output XML ONLY.
203
  """
204
- insight_msgs = [{"role":"system", "content":insight_sys_prompt}, {"role":"user", "content":insight_user_prompt}]
205
- insight_prov, insight_model_disp = provider, model_disp_name
206
- insight_env_model = os.getenv("INSIGHT_MODEL_OVERRIDE")
207
- if insight_env_model and "/" in insight_env_model:
208
- i_p, i_id = insight_env_model.split('/', 1)
209
- i_d_n = next((dn for dn, mid in MODELS_BY_PROVIDER.get(i_p.lower(), {}).get("models", {}).items() if mid == i_id), None)
210
- if i_d_n: insight_prov, insight_model_disp = i_p, i_d_n
211
- raw_ops_xml_full = "".join(list(call_model_stream(provider=insight_prov, model_display_name=insight_model_disp, messages=insight_msgs, api_key_override=api_key_override, temperature=0.0, max_tokens=3500))).strip()
212
- xml_match = re.search(r"<operations_list>.*</operations_list>", raw_ops_xml_full, re.DOTALL | re.IGNORECASE)
213
- if not xml_match:
214
- logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: No valid XML operations found.")
215
- return
216
- try:
217
- root = ET.fromstring(xml_match.group(0))
218
- for op_element in root.findall("operation"):
219
- action = op_element.find("action").text.strip().lower() if op_element.find("action") is not None and op_element.find("action").text else None
220
- insight_text = op_element.find("insight").text.strip() if op_element.find("insight") is not None and op_element.find("insight").text else None
221
- if not action or not insight_text: continue
222
- if action == "add":
223
- add_rule_entry(insight_text)
224
- elif action == "update":
225
- old_insight_text = op_element.find("old_insight_to_replace").text.strip() if op_element.find("old_insight_to_replace") is not None and op_element.find("old_insight_to_replace").text else None
226
- if old_insight_text:
227
- remove_rule_entry(old_insight_text)
228
- add_rule_entry(insight_text)
229
- except Exception as e:
230
- logger.error(f"POST_INTERACTION_LEARNING [{task_id}]: Error processing insight XML: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
  def handle_gradio_chat_submit(user_msg_txt: str, gr_hist_list: list, sel_prov_name: str, sel_model_disp_name: str, ui_api_key: str|None, cust_sys_prompt: str):
233
  global current_chat_session_history
234
  cleared_input, updated_gr_hist, status_txt = "", list(gr_hist_list), "Initializing..."
235
- updated_rules_text = ui_refresh_rules_display_fn()
236
- updated_mems_json = ui_refresh_memories_display_fn()
 
237
  def_detect_out_md = gr.Markdown(visible=False)
238
- def_fmt_out_txt = gr.Textbox(value="*Waiting...*", interactive=True)
239
  def_dl_btn = gr.DownloadButton(interactive=False, value=None, visible=False)
240
 
241
  if not user_msg_txt.strip():
242
- yield (cleared_input, updated_gr_hist, "Error: Empty message.", def_detect_out_md, def_fmt_out_txt, def_dl_btn, updated_rules_text, updated_mems_json)
 
 
 
243
  return
244
 
245
  updated_gr_hist.append((user_msg_txt, "<i>Thinking...</i>"))
 
246
  yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn, updated_rules_text, updated_mems_json)
247
 
248
- internal_hist = list(current_chat_session_history)
249
- internal_hist.append({"role": "user", "content": user_msg_txt})
250
-
 
 
 
 
 
251
  final_bot_resp_acc, insights_used_parsed = "", []
252
  temp_dl_file_path = None
253
 
@@ -258,114 +406,719 @@ def handle_gradio_chat_submit(user_msg_txt: str, gr_hist_list: list, sel_prov_na
258
  if upd_type == "status":
259
  status_txt = upd_data
260
  if updated_gr_hist and updated_gr_hist[-1][0] == user_msg_txt:
 
261
  updated_gr_hist[-1] = (user_msg_txt, f"{curr_bot_disp_msg} <i>{status_txt}</i>" if curr_bot_disp_msg else f"<i>{status_txt}</i>")
262
  elif upd_type == "response_chunk":
263
  curr_bot_disp_msg += upd_data
264
  if updated_gr_hist and updated_gr_hist[-1][0] == user_msg_txt:
265
- updated_gr_hist[-1] = (user_msg_txt, curr_bot_disp_msg)
266
  elif upd_type == "final_response_and_insights":
267
  final_bot_resp_acc, insights_used_parsed = upd_data["response"], upd_data["insights_used"]
268
  status_txt = "Response generated. Processing learning..."
 
 
269
  if updated_gr_hist and updated_gr_hist[-1][0] == user_msg_txt:
270
- updated_gr_hist[-1] = (user_msg_txt, final_bot_resp_acc or "(No text)")
271
-
272
- def_fmt_out_txt = gr.Textbox(value=final_bot_resp_acc, interactive=True)
273
- if final_bot_resp_acc and not final_bot_resp_acc.startswith("Error:"):
274
- with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".md", encoding='utf-8') as tmpfile:
275
- tmpfile.write(final_bot_resp_acc)
276
- temp_dl_file_path = tmpfile.name
277
- def_dl_btn = gr.DownloadButton(value=temp_dl_file_path, visible=True, interactive=True)
278
-
279
- insights_md_content = "### Insights Considered:\n" + ("\n".join([f"- **[{i.get('type','N/A')}|{i.get('score','N/A')}]** {i.get('text','N/A')[:100]}..." for i in insights_used_parsed[:3]]) if insights_used_parsed else "*None.*")
280
- def_detect_out_md = gr.Markdown(value=insights_md_content, visible=True)
281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn, updated_rules_text, updated_mems_json)
 
 
283
  if upd_type == "final_response_and_insights": break
 
284
  except Exception as e:
285
- status_txt = f"Error: {str(e)[:100]}"
286
- updated_gr_hist.append((user_msg_txt, f"Sorry, an error occurred: {status_txt}"))
287
- yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn, updated_rules_text, updated_mems_json)
288
- return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
 
 
290
  if final_bot_resp_acc and not final_bot_resp_acc.startswith("Error:"):
 
291
  current_chat_session_history.extend([{"role": "user", "content": user_msg_txt}, {"role": "assistant", "content": final_bot_resp_acc}])
292
- if len(current_chat_session_history) > MAX_HISTORY_TURNS * 2:
293
- current_chat_session_history = current_chat_session_history[-(MAX_HISTORY_TURNS * 2):]
 
 
 
294
 
295
- yield (cleared_input, updated_gr_hist, "<i>[Performing post-interaction learning...]</i>", def_detect_out_md, def_fmt_out_txt, def_dl_btn, updated_rules_text, updated_mems_json)
296
- perform_post_interaction_learning(user_input=user_msg_txt, bot_response=final_bot_resp_acc, provider=sel_prov_name, model_disp_name=sel_model_disp_name, insights_reflected=insights_used_parsed, api_key_override=ui_api_key.strip() if ui_api_key else None)
297
- status_txt = "Response & Learning Complete."
298
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
  updated_rules_text = ui_refresh_rules_display_fn()
300
  updated_mems_json = ui_refresh_memories_display_fn()
 
301
  yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn, updated_rules_text, updated_mems_json)
 
 
302
  if temp_dl_file_path and os.path.exists(temp_dl_file_path):
303
  try: os.unlink(temp_dl_file_path)
304
- except: pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
305
 
 
306
  def ui_refresh_rules_display_fn(): return "\n\n---\n\n".join(get_all_rules_cached()) or "No rules found."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
  def ui_refresh_memories_display_fn(): return get_all_memories_cached() or []
308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  def app_load_fn():
 
310
  initialize_memory_system()
311
- return "AI Systems Initialized. Ready.", ui_refresh_rules_display_fn(), ui_refresh_memories_display_fn()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
312
 
313
- with gr.Blocks(theme=gr.themes.Soft(), css=".gr-json { max-height: 300px; overflow-y: auto; }") as demo:
314
- gr.Markdown("# πŸ€– AI Research Agent")
315
  with gr.Row(variant="compact"):
316
- agent_stat_tb = gr.Textbox(label="Agent Status", value="Initializing...", interactive=False, scale=4)
 
 
 
317
  with gr.Column(scale=1, min_width=150):
318
- gr.Textbox(label="Memory Backend", value=MEMORY_STORAGE_BACKEND, interactive=False)
319
- gr.Textbox(label="SQLite Path", value=MEMORY_SQLITE_PATH, interactive=False, visible=MEMORY_STORAGE_BACKEND == "SQLITE")
320
- gr.Textbox(label="HF Repos", value=f"M: {MEMORY_HF_MEM_REPO}, R: {MEMORY_HF_RULES_REPO}", interactive=False, visible=MEMORY_STORAGE_BACKEND == "HF_DATASET")
 
 
 
 
 
 
 
 
 
 
321
  with gr.Row():
322
  with gr.Sidebar():
323
  gr.Markdown("## βš™οΈ Configuration")
324
- api_key_tb = gr.Textbox(label="API Key (Override)", type="password")
325
- available_providers = get_available_providers()
326
- prov_sel_dd = gr.Dropdown(label="AI Provider", choices=available_providers, value=available_providers[0] if available_providers else None, interactive=True)
327
- model_sel_dd = gr.Dropdown(label="AI Model", choices=get_model_display_names_for_provider(prov_sel_dd.value) if prov_sel_dd.value else [], value=get_default_model_display_name_for_provider(prov_sel_dd.value) if prov_sel_dd.value else None, interactive=True)
328
- sys_prompt_tb = gr.Textbox(label="System Prompt", lines=8, value=DEFAULT_SYSTEM_PROMPT)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  with gr.Column(scale=3):
330
  with gr.Tabs():
331
  with gr.TabItem("πŸ’¬ Chat & Research"):
332
- main_chat_disp = gr.Chatbot(label="Chat", height=400, show_copy_button=True, render_markdown=True)
333
- user_msg_tb = gr.Textbox(placeholder="Ask a question...", scale=7)
334
- send_btn = gr.Button("Send", variant="primary")
335
- with gr.Accordion("πŸ“ Detailed Response & Insights", open=False):
336
- fmt_report_tb = gr.Textbox(label="Full AI Response", lines=8, interactive=True, show_copy_button=True)
337
- dl_report_btn = gr.DownloadButton("Download Report", interactive=False, visible=False)
338
- detect_out_md = gr.Markdown(visible=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  with gr.TabItem("🧠 Knowledge Base"):
340
- with gr.Row():
341
  with gr.Column():
342
- rules_disp_ta = gr.TextArea(label="Current Rules", lines=10, interactive=True)
 
 
 
 
 
 
343
  save_edited_rules_btn = gr.Button("πŸ’Ύ Save Edited Text", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
344
  with gr.Column():
345
- mems_disp_json = gr.JSON(label="Current Memories")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
 
347
  def dyn_upd_model_dd(sel_prov_dyn: str):
348
- models = get_model_display_names_for_provider(sel_prov_dyn)
349
- default_model = get_default_model_display_name_for_provider(sel_prov_dyn)
350
- return gr.Dropdown(choices=models, value=default_model, interactive=True)
 
351
  prov_sel_dd.change(fn=dyn_upd_model_dd, inputs=prov_sel_dd, outputs=model_sel_dd)
352
 
 
353
  chat_ins = [user_msg_tb, main_chat_disp, prov_sel_dd, model_sel_dd, api_key_tb, sys_prompt_tb]
 
354
  chat_outs = [user_msg_tb, main_chat_disp, agent_stat_tb, detect_out_md, fmt_report_tb, dl_report_btn, rules_disp_ta, mems_disp_json]
355
-
356
- send_btn.click(fn=handle_gradio_chat_submit, inputs=chat_ins, outputs=chat_outs)
357
- user_msg_tb.submit(fn=handle_gradio_chat_submit, inputs=chat_ins, outputs=chat_outs)
358
-
359
- def save_rules_from_editor(text):
360
- for line in text.splitlines():
361
- if line.strip(): add_rule_entry(line.strip())
362
- return ui_refresh_rules_display_fn()
363
- save_edited_rules_btn.click(fn=save_rules_from_editor, inputs=[rules_disp_ta], outputs=[rules_disp_ta])
364
-
365
- demo.load(fn=app_load_fn, outputs=[agent_stat_tb, rules_disp_ta, mems_disp_json])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
 
367
  if __name__ == "__main__":
368
- logger.info(f"Starting Gradio AI Research Agent (Memory: {MEMORY_STORAGE_TYPE})...")
369
  app_port = int(os.getenv("GRADIO_PORT", 7860))
370
  app_server = os.getenv("GRADIO_SERVER_NAME", "127.0.0.1")
371
- demo.queue().launch(server_name=app_server, server_port=app_port, share=False)
 
 
 
 
 
1
+ # app.py
2
  import os
3
  import json
4
  import re
 
13
  load_dotenv()
14
 
15
  MEMORY_STORAGE_TYPE = "HF_DATASET"
16
+ # --- DEMO --- #
17
+ # If using HF_DATASET, specify the repository names here.
18
+ # These will override the .env file settings.
19
  HF_DATASET_MEMORY_REPO = "broadfield-dev/ai-brain"
20
  HF_DATASET_RULES_REPO = "broadfield-dev/ai-rules"
21
 
22
+ # Set environment variables based on the toggles above BEFORE importing other modules
23
  os.environ['STORAGE_BACKEND'] = MEMORY_STORAGE_TYPE
24
  if MEMORY_STORAGE_TYPE == "HF_DATASET":
25
  os.environ['HF_MEMORY_DATASET_REPO'] = HF_DATASET_MEMORY_REPO
26
  os.environ['HF_RULES_DATASET_REPO'] = HF_DATASET_RULES_REPO
27
+ # --- END CONFIGURATION ---
28
 
29
  from model_logic import (
30
  get_available_providers, get_model_display_names_for_provider,
31
  get_default_model_display_name_for_provider, call_model_stream, MODELS_BY_PROVIDER
32
  )
33
  from memory_logic import (
34
+ initialize_memory_system,
35
+ add_memory_entry, retrieve_memories_semantic, get_all_memories_cached, clear_all_memory_data_backend,
36
+ add_rule_entry, retrieve_rules_semantic, remove_rule_entry, get_all_rules_cached, clear_all_rules_data_backend,
37
+ save_faiss_indices_to_disk, STORAGE_BACKEND as MEMORY_STORAGE_BACKEND, SQLITE_DB_PATH as MEMORY_SQLITE_PATH,
38
+ HF_MEMORY_DATASET_REPO as MEMORY_HF_MEM_REPO, HF_RULES_DATASET_REPO as MEMORY_HF_RULES_REPO
 
 
39
  )
40
  from websearch_logic import scrape_url, search_and_scrape_duckduckgo, search_and_scrape_google
41
 
 
55
  "Your Name is Node. You are a Helpful AI Assistant, and your goal is to improve yourself, so that you can improve everybody elses life. Your job is to answer questions and perform research tasks accurately and thoroughly. You can use tools like web search and page browsing. When providing information from the web, cite your sources if possible. If asked to perform a task beyond your capabilities, explain politely. Be concise unless asked for detail."
56
  )
57
 
58
+ # --- Startup Loading File Paths ---
59
  LOAD_RULES_FILE = os.getenv("LOAD_RULES_FILE")
60
  LOAD_MEMORIES_FILE = os.getenv("LOAD_MEMORIES_FILE")
61
+ logger.info(f"App Config: WebSearch={WEB_SEARCH_ENABLED}, ToolDecisionProvider={TOOL_DECISION_PROVIDER_ENV}, ToolDecisionModelID={TOOL_DECISION_MODEL_ID_ENV}, MemoryBackend={MEMORY_STORAGE_BACKEND}")
62
+ logger.info(f"Startup loading: Rules from {LOAD_RULES_FILE or 'None'}, Memories from {LOAD_MEMORIES_FILE or 'None'}")
63
 
64
+
65
+ # --- Helper Functions ---
66
  def format_insights_for_prompt(retrieved_insights_list: list[str]) -> tuple[str, list[dict]]:
67
+ if not retrieved_insights_list:
68
+ return "No specific guiding principles or learned insights retrieved.", []
69
  parsed = []
70
  for text in retrieved_insights_list:
71
  match = re.match(r"\[(CORE_RULE|RESPONSE_PRINCIPLE|BEHAVIORAL_ADJUSTMENT|GENERAL_LEARNING)\|([\d\.]+?)\](.*)", text.strip(), re.DOTALL | re.IGNORECASE)
 
75
  parsed.append({"type": "GENERAL_LEARNING", "score": "0.5", "text": text.strip(), "original": text.strip()})
76
  try:
77
  parsed.sort(key=lambda x: float(x["score"]) if x["score"].replace('.', '', 1).isdigit() else -1.0, reverse=True)
78
+ except ValueError: logger.warning("FORMAT_INSIGHTS: Sort error due to invalid score format.")
79
  grouped = {"CORE_RULE": [], "RESPONSE_PRINCIPLE": [], "BEHAVIORAL_ADJUSTMENT": [], "GENERAL_LEARNING": []}
80
  for p_item in parsed: grouped.get(p_item["type"], grouped["GENERAL_LEARNING"]).append(f"- (Score: {p_item['score']}) {p_item['text']}")
81
  sections = [f"{k.replace('_', ' ').title()}:\n" + "\n".join(v) for k, v in grouped.items() if v]
82
  return "\n\n".join(sections) if sections else "No guiding principles retrieved.", parsed
83
 
84
  def generate_interaction_metrics(user_input: str, bot_response: str, provider: str, model_display_name: str, api_key_override: str = None) -> dict:
85
+ metric_start_time = time.time()
86
+ logger.info(f"Generating metrics with: {provider}/{model_display_name}")
87
+ metric_prompt_content = f"User: \"{user_input}\"\nAI: \"{bot_response}\"\nMetrics: \"takeaway\" (3-7 words), \"response_success_score\" (0.0-1.0), \"future_confidence_score\" (0.0-1.0). Output JSON ONLY, ensure it's a single, valid JSON object."
88
+ metric_messages = [{"role": "system", "content": "You are a precise JSON output agent. Output a single JSON object containing interaction metrics as requested by the user. Do not include any explanatory text before or after the JSON object."}, {"role": "user", "content": metric_prompt_content}]
89
  try:
90
+ metrics_provider_final, metrics_model_display_final = provider, model_display_name
91
  metrics_model_env = os.getenv("METRICS_MODEL")
92
  if metrics_model_env and "/" in metrics_model_env:
93
  m_prov, m_id = metrics_model_env.split('/', 1)
94
  m_disp_name = next((dn for dn, mid in MODELS_BY_PROVIDER.get(m_prov.lower(), {}).get("models", {}).items() if mid == m_id), None)
95
+ if m_disp_name: metrics_provider_final, metrics_model_display_final = m_prov, m_disp_name
96
+ else: logger.warning(f"METRICS_MODEL '{metrics_model_env}' not found, using interaction model.")
97
+ response_chunks = list(call_model_stream(provider=metrics_provider_final, model_display_name=metrics_model_display_final, messages=metric_messages, api_key_override=api_key_override, temperature=0.05, max_tokens=200))
98
+ resp_str = "".join(response_chunks).strip()
99
+ json_match = re.search(r"```json\s*(\{.*?\})\s*```", resp_str, re.DOTALL | re.IGNORECASE) or re.search(r"(\{.*?\})", resp_str, re.DOTALL)
100
+ if json_match: metrics_data = json.loads(json_match.group(1))
101
+ else:
102
+ logger.warning(f"METRICS_GEN: Non-JSON response from {metrics_provider_final}/{metrics_model_display_final}: '{resp_str}'")
103
+ return {"takeaway": "N/A", "response_success_score": 0.5, "future_confidence_score": 0.5, "error": "metrics format error"}
104
+ parsed_metrics = {"takeaway": metrics_data.get("takeaway", "N/A"), "response_success_score": float(metrics_data.get("response_success_score", 0.5)), "future_confidence_score": float(metrics_data.get("future_confidence_score", 0.5)), "error": metrics_data.get("error")}
105
+ logger.info(f"METRICS_GEN: Generated in {time.time() - metric_start_time:.2f}s. Data: {parsed_metrics}")
106
+ return parsed_metrics
107
  except Exception as e:
108
+ logger.error(f"METRICS_GEN Error: {e}", exc_info=False)
109
+ return {"takeaway": "N/A", "response_success_score": 0.5, "future_confidence_score": 0.5, "error": str(e)}
110
+
111
 
112
  def process_user_interaction_gradio(user_input: str, provider_name: str, model_display_name: str, chat_history_for_prompt: list[dict], custom_system_prompt: str = None, ui_api_key_override: str = None):
113
+ process_start_time = time.time()
114
  request_id = os.urandom(4).hex()
115
+ logger.info(f"PUI_GRADIO [{request_id}] Start. User: '{user_input[:50]}...' Provider: {provider_name}/{model_display_name} Hist_len:{len(chat_history_for_prompt)}")
116
  history_str_for_prompt = "\n".join([f"{('User' if t_msg['role'] == 'user' else 'AI')}: {t_msg['content']}" for t_msg in chat_history_for_prompt[-(MAX_HISTORY_TURNS * 2):]])
117
+ yield "status", "<i>[Checking guidelines (semantic search)...]</i>"
118
+ initial_insights = retrieve_rules_semantic(f"{user_input}\n{history_str_for_prompt}", k=5)
119
+ initial_insights_ctx_str, parsed_initial_insights_list = format_insights_for_prompt(initial_insights)
120
+ logger.info(f"PUI_GRADIO [{request_id}]: Initial RAG (insights) found {len(initial_insights)}. Context: {initial_insights_ctx_str[:150]}...")
121
+ action_type, action_input_dict = "quick_respond", {}
122
+ user_input_lower = user_input.lower()
123
+ time_before_tool_decision = time.time()
124
+ if WEB_SEARCH_ENABLED and ("http://" in user_input or "https://" in user_input):
125
+ url_match = re.search(r'(https?://[^\s]+)', user_input)
126
+ if url_match: action_type, action_input_dict = "scrape_url_and_report", {"url": url_match.group(1)}
127
+ if action_type == "quick_respond" and len(user_input.split()) <= 3 and any(kw in user_input_lower for kw in ["hello", "hi", "thanks", "ok", "bye"]) and not "?" in user_input: pass
128
+ elif action_type == "quick_respond" and WEB_SEARCH_ENABLED and (len(user_input.split()) > 3 or "?" in user_input or any(w in user_input_lower for w in ["what is", "how to", "explain", "search for"])):
129
  yield "status", "<i>[LLM choosing best approach...]</i>"
130
+ history_snippet = "\n".join([f"{msg['role']}: {msg['content'][:100]}" for msg in chat_history_for_prompt[-2:]])
131
+ guideline_snippet = initial_insights_ctx_str[:200].replace('\n', ' ')
132
+ tool_sys_prompt = "You are a precise routing agent... Output JSON only. Example: {\"action\": \"search_duckduckgo_and_report\", \"action_input\": {\"search_engine_query\": \"query\"}}"
133
+ tool_user_prompt = f"User Query: \"{user_input}\nRecent History:\n{history_snippet}\nGuidelines: {guideline_snippet}...\nAvailable Actions: quick_respond, answer_using_conversation_memory, search_duckduckgo_and_report, scrape_url_and_report.\nSelect one action and input. Output JSON."
134
+ tool_decision_messages = [{"role":"system", "content": tool_sys_prompt}, {"role":"user", "content": tool_user_prompt}]
 
 
 
 
 
135
  tool_provider, tool_model_id = TOOL_DECISION_PROVIDER_ENV, TOOL_DECISION_MODEL_ID_ENV
136
  tool_model_display = next((dn for dn, mid in MODELS_BY_PROVIDER.get(tool_provider.lower(), {}).get("models", {}).items() if mid == tool_model_id), None)
137
  if not tool_model_display: tool_model_display = get_default_model_display_name_for_provider(tool_provider)
138
+ if tool_model_display:
139
+ try:
140
+ logger.info(f"PUI_GRADIO [{request_id}]: Tool decision LLM: {tool_provider}/{tool_model_display}")
141
+ tool_resp_chunks = list(call_model_stream(provider=tool_provider, model_display_name=tool_model_display, messages=tool_decision_messages, temperature=0.0, max_tokens=150))
142
+ tool_resp_raw = "".join(tool_resp_chunks).strip()
143
+ json_match_tool = re.search(r"\{.*\}", tool_resp_raw, re.DOTALL)
144
+ if json_match_tool:
145
+ action_data = json.loads(json_match_tool.group(0))
146
+ action_type, action_input_dict = action_data.get("action", "quick_respond"), action_data.get("action_input", {})
147
+ if not isinstance(action_input_dict, dict): action_input_dict = {}
148
+ logger.info(f"PUI_GRADIO [{request_id}]: LLM Tool Decision: Action='{action_type}', Input='{action_input_dict}'")
149
+ else: logger.warning(f"PUI_GRADIO [{request_id}]: Tool decision LLM non-JSON. Raw: {tool_resp_raw}")
150
+ except Exception as e: logger.error(f"PUI_GRADIO [{request_id}]: Tool decision LLM error: {e}", exc_info=False)
151
+ else: logger.error(f"No model for tool decision provider {tool_provider}.")
152
+ elif action_type == "quick_respond" and not WEB_SEARCH_ENABLED and (len(user_input.split()) > 4 or "?" in user_input or any(w in user_input_lower for w in ["remember","recall"])):
153
+ action_type="answer_using_conversation_memory"
154
+ logger.info(f"PUI_GRADIO [{request_id}]: Tool decision logic took {time.time() - time_before_tool_decision:.3f}s. Action: {action_type}, Input: {action_input_dict}")
155
  yield "status", f"<i>[Path: {action_type}. Preparing response...]</i>"
156
+ final_system_prompt_str, final_user_prompt_content_str = custom_system_prompt or DEFAULT_SYSTEM_PROMPT, ""
157
+ if action_type == "quick_respond":
158
+ final_system_prompt_str += " Respond directly using guidelines & history."
159
+ final_user_prompt_content_str = f"History:\n{history_str_for_prompt}\nGuidelines:\n{initial_insights_ctx_str}\nQuery: \"{user_input}\"\nResponse:"
160
+ elif action_type == "answer_using_conversation_memory":
161
+ yield "status", "<i>[Searching conversation memory (semantic)...]</i>"
162
+ retrieved_mems = retrieve_memories_semantic(f"User query: {user_input}\nContext:\n{history_str_for_prompt[-1000:]}", k=2)
163
+ memory_context = "Relevant Past Interactions:\n" + "\n".join([f"- User:{m.get('user_input','')}->AI:{m.get('bot_response','')} (Takeaway:{m.get('metrics',{}).get('takeaway','N/A')})" for m in retrieved_mems]) if retrieved_mems else "No relevant past interactions found."
164
+ final_system_prompt_str += " Respond using Memory Context, guidelines, & history."
165
+ final_user_prompt_content_str = f"History:\n{history_str_for_prompt}\nGuidelines:\n{initial_insights_ctx_str}\nMemory Context:\n{memory_context}\nQuery: \"{user_input}\"\nResponse (use memory context if relevant):"
166
+ elif WEB_SEARCH_ENABLED and action_type in ["search_duckduckgo_and_report", "scrape_url_and_report"]:
167
+ query_or_url = action_input_dict.get("search_engine_query") if "search" in action_type else action_input_dict.get("url")
168
+ if not query_or_url:
169
+ final_system_prompt_str += " Respond directly (web action failed: no input)."
170
+ final_user_prompt_content_str = f"History:\n{history_str_for_prompt}\nGuidelines:\n{initial_insights_ctx_str}\nQuery: \"{user_input}\"\nResponse:"
171
+ else:
172
+ yield "status", f"<i>[Web: '{query_or_url[:60]}'...]</i>"
173
+ web_results, max_results = [], 1 if action_type == "scrape_url_and_report" else 2
174
+ try:
175
+ if action_type == "search_duckduckgo_and_report": web_results = search_and_scrape_duckduckgo(query_or_url, num_results=max_results)
176
+ elif action_type == "scrape_url_and_report":
177
+ res = scrape_url(query_or_url)
178
+ if res and (res.get("content") or res.get("error")): web_results = [res]
179
+ except Exception as e: web_results = [{"url": query_or_url, "title": "Tool Error", "error": str(e)}]
180
+ scraped_content = "\n".join([f"Source {i+1}:\nURL:{r.get('url','N/A')}\nTitle:{r.get('title','N/A')}\nContent:\n{(r.get('content') or r.get('error') or 'N/A')[:3500]}\n---" for i,r in enumerate(web_results)]) if web_results else f"No results from {action_type} for '{query_or_url}'."
181
+ yield "status", "<i>[Synthesizing web report...]</i>"
182
+ final_system_prompt_str += " Generate report/answer from web content, history, & guidelines. Cite URLs as [Source X]."
183
+ final_user_prompt_content_str = f"History:\n{history_str_for_prompt}\nGuidelines:\n{initial_insights_ctx_str}\nWeb Content:\n{scraped_content}\nQuery: \"{user_input}\"\nReport/Response (cite sources [Source X]):"
 
 
 
 
 
184
  else:
185
+ final_system_prompt_str += " Respond directly (unknown action path)."
186
+ final_user_prompt_content_str = f"History:\n{history_str_for_prompt}\nGuidelines:\n{initial_insights_ctx_str}\nQuery: \"{user_input}\"\nResponse:"
187
  final_llm_messages = [{"role": "system", "content": final_system_prompt_str}, {"role": "user", "content": final_user_prompt_content_str}]
188
+ logger.debug(f"PUI_GRADIO [{request_id}]: Final LLM System Prompt: {final_system_prompt_str[:200]}...")
189
+ logger.debug(f"PUI_GRADIO [{request_id}]: Final LLM User Prompt Start: {final_user_prompt_content_str[:200]}...")
190
+ streamed_response, time_before_llm = "", time.time()
191
+ try:
192
+ for chunk in call_model_stream(provider=provider_name, model_display_name=model_display_name, messages=final_llm_messages, api_key_override=ui_api_key_override, temperature=0.6, max_tokens=2500):
193
+ if isinstance(chunk, str) and chunk.startswith("Error:"): streamed_response += f"\n{chunk}\n"; yield "response_chunk", f"\n{chunk}\n"; break
194
+ streamed_response += chunk; yield "response_chunk", chunk
195
+ except Exception as e: streamed_response += f"\n\n(Error: {str(e)[:150]})"; yield "response_chunk", f"\n\n(Error: {str(e)[:150]})"
196
+ logger.info(f"PUI_GRADIO [{request_id}]: Main LLM stream took {time.time() - time_before_llm:.3f}s.")
197
+ final_bot_text = streamed_response.strip() or "(No response or error.)"
198
+ logger.info(f"PUI_GRADIO [{request_id}]: Finished. Total: {time.time() - process_start_time:.2f}s. Resp len: {len(final_bot_text)}")
199
  yield "final_response_and_insights", {"response": final_bot_text, "insights_used": parsed_initial_insights_list}
200
 
201
  def perform_post_interaction_learning(user_input: str, bot_response: str, provider: str, model_disp_name: str, insights_reflected: list[dict], api_key_override: str = None):
202
  task_id = os.urandom(4).hex()
203
+ logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: START User='{user_input[:40]}...', Bot='{bot_response[:40]}...'")
204
+ learning_start_time = time.time()
205
+ significant_learnings_summary = [] # To store summaries of new core learnings
206
+
207
+ try:
208
+ metrics = generate_interaction_metrics(user_input, bot_response, provider, model_disp_name, api_key_override)
209
+ logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: Metrics: {metrics}")
210
+ add_memory_entry(user_input, metrics, bot_response)
211
+
212
+ summary = f"User:\"{user_input}\"\nAI:\"{bot_response}\"\nMetrics(takeaway):{metrics.get('takeaway','N/A')},Success:{metrics.get('response_success_score','N/A')}"
213
+ existing_rules_ctx = "\n".join([f"- \"{r}\"" for r in retrieve_rules_semantic(f"{summary}\n{user_input}", k=10)]) or "No existing rules context."
214
+
215
+ insight_sys_prompt = """You are an expert AI knowledge base curator. Your primary function is to meticulously analyze an interaction and update the AI's guiding principles (insights/rules) to improve its future performance and self-understanding.
216
  **CRITICAL OUTPUT REQUIREMENT: You MUST output a single, valid XML structure representing a list of operation objects.**
217
  The root element should be `<operations_list>`. Each operation should be an `<operation>` element.
218
  If no operations are warranted, output an empty list: `<operations_list></operations_list>`.
 
221
  1. `<action>`: A string, either `"add"` (for entirely new rules) or `"update"` (to replace an existing rule with a better one).
222
  2. `<insight>`: The full, refined insight text including its `[TYPE|SCORE]` prefix (e.g., `[CORE_RULE|1.0] My name is Lumina, an AI assistant.`). Multi-line insight text can be placed directly within this tag; XML handles newlines naturally.
223
  3. `<old_insight_to_replace>`: (ONLY for `"update"` action) The *exact, full text* of an existing insight that the new `<insight>` should replace. If action is `"add"`, this element should be omitted or empty.
224
+ **XML Structure Example:**
225
+ <operations_list>
226
+ <operation>
227
+ <action>update</action>
228
+ <insight>[CORE_RULE|1.0] I am Lumina, an AI assistant.
229
+ My purpose is to help with research.</insight>
230
+ <old_insight_to_replace>[CORE_RULE|0.9] My name is Assistant.</old_insight_to_replace>
231
+ </operation>
232
+ <operation>
233
+ <action>add</action>
234
+ <insight>[RESPONSE_PRINCIPLE|0.8] User prefers short answers.
235
+ Provide details only when asked.</insight>
236
+ </operation>
237
+ </operations_list>
238
+ **Your Reflection Process (Consider each step and generate operations accordingly):**
239
+ - **STEP 1: CORE IDENTITY/PURPOSE:** Review the interaction and existing rules. Identify if the interaction conflicts with, clarifies, or reinforces your core identity (name, fundamental nature, primary purpose). If necessary, propose updates or additions to CORE_RULEs. Aim for a single, consistent set of CORE_RULEs over time by updating older versions.
240
+ - **STEP 2: NEW LEARNINGS:** Based *only* on the "Interaction Summary", identify concrete, factual information, user preferences, or skills demonstrated that were not previously known or captured. These should be distinct, actionable learnings. Formulate these as new [GENERAL_LEARNING] or specific [BEHAVIORAL_ADJUSTMENT] rules. Do NOT add rules that are already covered by existing relevant rules.
241
+ - **STEP 3: REFINEMENT/ADJUSTMENT:** Review existing non-core rules ([RESPONSE_PRINCIPLE], [BEHAVIORAL_ADJUSTMENT], [GENERAL_LEARNING]) retrieved as "Potentially Relevant Existing Rules". Determine if the interaction indicates any of these rules need refinement, adjustment, or correction. Update existing rules if a better version exists.
242
+ **General Guidelines for Insight Content and Actions:**
243
+ - Ensure the `<insight>` field always contains the properly formatted insight string: `[TYPE|SCORE] Text`.
244
+ - Be precise with `<old_insight_to_replace>` – it must *exactly* match an existing rule string.
245
+ - Aim for a comprehensive set of operations.
246
  """
247
+ insight_user_prompt = f"""Interaction Summary:\n{summary}\n
248
  Potentially Relevant Existing Rules (Review these carefully. Your main goal is to consolidate CORE_RULEs and then identify other changes/additions based on the Interaction Summary and these existing rules):\n{existing_rules_ctx}\n
249
  Guiding principles that were considered during THIS interaction (these might offer clues for new rules or refinements):\n{json.dumps([p['original'] for p in insights_reflected if 'original' in p]) if insights_reflected else "None"}\n
250
+ Task: Based on your three-step reflection process (Core Identity, New Learnings, Refinements):
251
+ 1. **Consolidate CORE_RULEs:** Merge similar identity/purpose rules from "Potentially Relevant Existing Rules" into single, definitive statements using "update" operations. Replace multiple old versions with the new canonical one.
252
+ 2. **Add New Learnings:** Identify and "add" any distinct new facts, skills, or important user preferences learned from the "Interaction Summary".
253
+ 3. **Update Existing Principles:** "Update" any non-core principles from "Potentially Relevant Existing Rules" if the "Interaction Summary" provided a clear refinement.
254
+ Combine all findings into a single, valid XML structure as specified in the system prompt (root `<operations_list>`, with child `<operation>` elements). Output XML ONLY.
255
  """
256
+ insight_msgs = [{"role":"system", "content":insight_sys_prompt}, {"role":"user", "content":insight_user_prompt}]
257
+ insight_prov, insight_model_disp = provider, model_disp_name
258
+ insight_env_model = os.getenv("INSIGHT_MODEL_OVERRIDE")
259
+ if insight_env_model and "/" in insight_env_model:
260
+ i_p, i_id = insight_env_model.split('/', 1)
261
+ i_d_n = next((dn for dn, mid in MODELS_BY_PROVIDER.get(i_p.lower(), {}).get("models", {}).items() if mid == i_id), None)
262
+ if i_d_n: insight_prov, insight_model_disp = i_p, i_d_n
263
+ logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: Generating insights with {insight_prov}/{insight_model_disp} (expecting XML)")
264
+
265
+ raw_ops_xml_full = "".join(list(call_model_stream(provider=insight_prov, model_display_name=insight_model_disp, messages=insight_msgs, api_key_override=api_key_override, temperature=0.0, max_tokens=3500))).strip()
266
+
267
+ ops_data_list, processed_count = [], 0
268
+
269
+ xml_match = re.search(r"```xml\s*(<operations_list>.*</operations_list>)\s*```", raw_ops_xml_full, re.DOTALL | re.IGNORECASE) or \
270
+ re.search(r"(<operations_list>.*</operations_list>)", raw_ops_xml_full, re.DOTALL | re.IGNORECASE)
271
+
272
+ if xml_match:
273
+ xml_content_str = xml_match.group(1)
274
+ try:
275
+ root = ET.fromstring(xml_content_str)
276
+ if root.tag == "operations_list":
277
+ for op_element in root.findall("operation"):
278
+ action_el = op_element.find("action")
279
+ insight_el = op_element.find("insight")
280
+ old_insight_el = op_element.find("old_insight_to_replace")
281
+
282
+ action = action_el.text.strip().lower() if action_el is not None and action_el.text else None
283
+ insight_text = insight_el.text.strip() if insight_el is not None and insight_el.text else None
284
+ old_insight_text = old_insight_el.text.strip() if old_insight_el is not None and old_insight_el.text else None
285
+
286
+ if action and insight_text:
287
+ ops_data_list.append({
288
+ "action": action,
289
+ "insight": insight_text,
290
+ "old_insight_to_replace": old_insight_text
291
+ })
292
+ else:
293
+ logger.warning(f"POST_INTERACTION_LEARNING [{task_id}]: Skipped XML operation due to missing action or insight text. Action: {action}, Insight: {insight_text}")
294
+ else:
295
+ logger.error(f"POST_INTERACTION_LEARNING [{task_id}]: XML root tag is not <operations_list>. Found: {root.tag}. XML content:\n{xml_content_str}")
296
+ except ET.ParseError as e:
297
+ logger.error(f"POST_INTERACTION_LEARNING [{task_id}]: XML parsing error: {e}. XML content that failed:\n{xml_content_str}")
298
+ except Exception as e_xml_proc:
299
+ logger.error(f"POST_INTERACTION_LEARNING [{task_id}]: Error processing parsed XML: {e_xml_proc}. XML content:\n{xml_content_str}")
300
+ else:
301
+ logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: No <operations_list> XML structure found in LLM output. Full raw output:\n{raw_ops_xml_full}")
302
+
303
+ if ops_data_list:
304
+ logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: LLM provided {len(ops_data_list)} insight ops from XML.")
305
+ for op_idx, op_data in enumerate(ops_data_list):
306
+ action = op_data["action"]
307
+ insight_text = op_data["insight"]
308
+ old_insight = op_data["old_insight_to_replace"]
309
+
310
+ if not re.match(r"\[(CORE_RULE|RESPONSE_PRINCIPLE|BEHAVIORAL_ADJUSTMENT|GENERAL_LEARNING)\|([\d\.]+?)\]", insight_text, re.I|re.DOTALL):
311
+ logger.warning(f"POST_INTERACTION_LEARNING [{task_id}]: Op {op_idx}: Skipped op due to invalid insight_text format from XML: '{insight_text[:100]}...'")
312
+ continue
313
+
314
+ rule_added_or_updated = False
315
+ if action == "add":
316
+ success, status_msg = add_rule_entry(insight_text)
317
+ if success:
318
+ processed_count +=1
319
+ rule_added_or_updated = True
320
+ if insight_text.upper().startswith("[CORE_RULE"):
321
+ significant_learnings_summary.append(f"New Core Rule Added: {insight_text}")
322
+ else: logger.warning(f"POST_INTERACTION_LEARNING [{task_id}]: Op {op_idx} (add from XML): Failed to add rule '{insight_text[:50]}...'. Status: {status_msg}")
323
+ elif action == "update":
324
+ removed_old = False
325
+ if old_insight:
326
+ if old_insight != insight_text:
327
+ remove_success = remove_rule_entry(old_insight)
328
+ if not remove_success:
329
+ logger.warning(f"POST_INTERACTION_LEARNING [{task_id}]: Op {op_idx} (update from XML): Failed to remove old rule '{old_insight[:50]}...' before adding new.")
330
+ else:
331
+ removed_old = True
332
+ else:
333
+ logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: Op {op_idx} (update from XML): Old insight is identical to new insight. Skipping removal.")
334
+
335
+ success, status_msg = add_rule_entry(insight_text)
336
+ if success:
337
+ processed_count +=1
338
+ rule_added_or_updated = True
339
+ if insight_text.upper().startswith("[CORE_RULE"):
340
+ significant_learnings_summary.append(f"Core Rule Updated (Old: {'Removed' if removed_old else 'Not removed/Same'}, New: {insight_text})")
341
+ else: logger.warning(f"POST_INTERACTION_LEARNING [{task_id}]: Op {op_idx} (update from XML): Failed to add/update rule '{insight_text[:50]}...'. Status: {status_msg}")
342
+ else:
343
+ logger.warning(f"POST_INTERACTION_LEARNING [{task_id}]: Op {op_idx}: Skipped op due to unknown action '{action}' from XML.")
344
+
345
+ # After processing all rules, if there were significant learnings, add a special memory
346
+ if significant_learnings_summary:
347
+ learning_digest = "SYSTEM CORE LEARNING DIGEST:\n" + "\n".join(significant_learnings_summary)
348
+ # Create a synthetic metrics object for this system memory
349
+ system_metrics = {
350
+ "takeaway": "Core knowledge refined.",
351
+ "response_success_score": 1.0, # Assuming successful internal update
352
+ "future_confidence_score": 1.0,
353
+ "type": "SYSTEM_REFLECTION"
354
+ }
355
+ add_memory_entry(
356
+ user_input="SYSTEM_INTERNAL_REFLECTION_TRIGGER", # Fixed identifier
357
+ metrics=system_metrics,
358
+ bot_response=learning_digest
359
+ )
360
+ logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: Added CORE_LEARNING_DIGEST to memories: {learning_digest[:100]}...")
361
+
362
+ logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: Processed {processed_count} insight ops out of {len(ops_data_list)} received from XML.")
363
+ else:
364
+ logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: No valid insight operations derived from LLM's XML output.")
365
+
366
+ except Exception as e: logger.error(f"POST_INTERACTION_LEARNING [{task_id}]: CRITICAL ERROR in learning task: {e}", exc_info=True)
367
+ logger.info(f"POST_INTERACTION_LEARNING [{task_id}]: END. Total: {time.time() - learning_start_time:.2f}s")
368
+
369
 
370
  def handle_gradio_chat_submit(user_msg_txt: str, gr_hist_list: list, sel_prov_name: str, sel_model_disp_name: str, ui_api_key: str|None, cust_sys_prompt: str):
371
  global current_chat_session_history
372
  cleared_input, updated_gr_hist, status_txt = "", list(gr_hist_list), "Initializing..."
373
+ # Initialize all potential output components with default/current values
374
+ updated_rules_text = ui_refresh_rules_display_fn() # Get current rules state
375
+ updated_mems_json = ui_refresh_memories_display_fn() # Get current memories state
376
  def_detect_out_md = gr.Markdown(visible=False)
377
+ def_fmt_out_txt = gr.Textbox(value="*Waiting...*", interactive=True, show_copy_button=True)
378
  def_dl_btn = gr.DownloadButton(interactive=False, value=None, visible=False)
379
 
380
  if not user_msg_txt.strip():
381
+ status_txt = "Error: Empty message."
382
+ updated_gr_hist.append((user_msg_txt or "(Empty)", status_txt))
383
+ # Ensure all outputs are provided on early exit
384
+ yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn, updated_rules_text, updated_mems_json)
385
  return
386
 
387
  updated_gr_hist.append((user_msg_txt, "<i>Thinking...</i>"))
388
+ # Initial yield to update chat UI with thinking message and show current knowledge base state
389
  yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn, updated_rules_text, updated_mems_json)
390
 
391
+ internal_hist = list(current_chat_session_history); internal_hist.append({"role": "user", "content": user_msg_txt})
392
+ # History truncation logic (keep MAX_HISTORY_TURNS pairs + optional system prompt)
393
+ hist_len_check = MAX_HISTORY_TURNS * 2
394
+ if internal_hist and internal_hist[0]["role"] == "system": hist_len_check +=1
395
+ if len(internal_hist) > hist_len_check:
396
+ current_chat_session_history = ([internal_hist[0]] if internal_hist[0]["role"] == "system" else []) + internal_hist[-(MAX_HISTORY_TURNS * 2):]
397
+ internal_hist = list(current_chat_session_history) # Use truncated history for current turn processing
398
+
399
  final_bot_resp_acc, insights_used_parsed = "", []
400
  temp_dl_file_path = None
401
 
 
406
  if upd_type == "status":
407
  status_txt = upd_data
408
  if updated_gr_hist and updated_gr_hist[-1][0] == user_msg_txt:
409
+ # Update the status alongside the streaming message
410
  updated_gr_hist[-1] = (user_msg_txt, f"{curr_bot_disp_msg} <i>{status_txt}</i>" if curr_bot_disp_msg else f"<i>{status_txt}</i>")
411
  elif upd_type == "response_chunk":
412
  curr_bot_disp_msg += upd_data
413
  if updated_gr_hist and updated_gr_hist[-1][0] == user_msg_txt:
414
+ updated_gr_hist[-1] = (user_msg_txt, curr_bot_disp_msg) # Update chat with streamed chunk
415
  elif upd_type == "final_response_and_insights":
416
  final_bot_resp_acc, insights_used_parsed = upd_data["response"], upd_data["insights_used"]
417
  status_txt = "Response generated. Processing learning..."
418
+ # Ensure the final chat message reflects the full response
419
+ if not curr_bot_disp_msg and final_bot_resp_acc : curr_bot_disp_msg = final_bot_resp_acc
420
  if updated_gr_hist and updated_gr_hist[-1][0] == user_msg_txt:
421
+ updated_gr_hist[-1] = (user_msg_txt, curr_bot_disp_msg or "(No text)")
 
 
 
 
 
 
 
 
 
 
422
 
423
+ # Update detailed response box and download button
424
+ def_fmt_out_txt = gr.Textbox(value=curr_bot_disp_msg, interactive=True, show_copy_button=True)
425
+
426
+ if curr_bot_disp_msg and not curr_bot_disp_msg.startswith("Error:"):
427
+ try:
428
+ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".md", encoding='utf-8') as tmpfile:
429
+ tmpfile.write(curr_bot_disp_msg)
430
+ temp_dl_file_path = tmpfile.name
431
+ def_dl_btn = gr.DownloadButton(value=temp_dl_file_path, visible=True, interactive=True)
432
+ except Exception as e:
433
+ logger.error(f"Error creating temp file for download: {e}", exc_info=False)
434
+ def_dl_btn = gr.DownloadButton(interactive=False, value=None, visible=False, label="Download Error")
435
+ else:
436
+ def_dl_btn = gr.DownloadButton(interactive=False, value=None, visible=False)
437
+
438
+ # Update insights display
439
+ insights_md_content = "### Insights Considered (Pre-Response):\n" + ("\n".join([f"- **[{i.get('type','N/A')}|{i.get('score','N/A')}]** {i.get('text','N/A')[:100]}..." for i in insights_used_parsed[:3]]) if insights_used_parsed else "*None specific.*")
440
+ def_detect_out_md = gr.Markdown(value=insights_md_content, visible=True if insights_used_parsed else False)
441
+
442
+ # Yield intermediate updates for the UI
443
+ # Pass the *current* state of rules and memories display components
444
  yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn, updated_rules_text, updated_mems_json)
445
+
446
+ # Stop processing generator after final_response_and_insights
447
  if upd_type == "final_response_and_insights": break
448
+
449
  except Exception as e:
450
+ logger.error(f"Chat handler error during main processing: {e}", exc_info=True); status_txt = f"Error: {str(e)[:100]}"
451
+ error_message_for_chat = f"Sorry, an error occurred during response generation: {str(e)[:100]}"
452
+ if updated_gr_hist and updated_gr_hist[-1][0] == user_msg_txt:
453
+ updated_gr_hist[-1] = (user_msg_txt, error_message_for_chat)
454
+ else:
455
+ updated_gr_hist.append((user_msg_txt, error_message_for_chat))
456
+ def_fmt_out_txt = gr.Textbox(value=error_message_for_chat, interactive=True)
457
+ def_dl_btn = gr.DownloadButton(interactive=False, value=None, visible=False)
458
+ def_detect_out_md = gr.Markdown(value="*Error processing request.*", visible=True)
459
+
460
+ # Provide the current state of rules/memories on error path yield
461
+ current_rules_text_on_error = ui_refresh_rules_display_fn()
462
+ current_mems_json_on_error = ui_refresh_memories_display_fn()
463
+
464
+ yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn, current_rules_text_on_error, current_mems_json_on_error)
465
+ # Clean up temp file if created before error
466
+ if temp_dl_file_path and os.path.exists(temp_dl_file_path):
467
+ try: os.unlink(temp_dl_file_path)
468
+ except Exception as e_unlink: logger.error(f"Error deleting temp download file {temp_dl_file_path} after error: {e_unlink}")
469
+ return # Exit the function after error handling
470
 
471
+ # --- Post-Interaction Learning ---
472
  if final_bot_resp_acc and not final_bot_resp_acc.startswith("Error:"):
473
+ # Add the successful turn to the internal history
474
  current_chat_session_history.extend([{"role": "user", "content": user_msg_txt}, {"role": "assistant", "content": final_bot_resp_acc}])
475
+ # History truncation again after adding
476
+ hist_len_check = MAX_HISTORY_TURNS * 2
477
+ if current_chat_session_history and current_chat_session_history[0]["role"] == "system": hist_len_check +=1
478
+ if len(current_chat_session_history) > hist_len_check:
479
+ current_chat_session_history = ([current_chat_session_history[0]] if current_chat_session_history[0]["role"] == "system" else []) + current_chat_session_history[-(MAX_HISTORY_TURNS * 2):]
480
 
481
+ status_txt = "<i>[Performing post-interaction learning...]</i>"
482
+ # Yield status before synchronous learning
483
+ current_rules_text_before_learn = ui_refresh_rules_display_fn()
484
+ current_mems_json_before_learn = ui_refresh_memories_display_fn()
485
+ yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn, current_rules_text_before_learn, current_mems_json_before_learn)
486
+
487
+ try:
488
+ perform_post_interaction_learning(
489
+ user_input=user_msg_txt,
490
+ bot_response=final_bot_resp_acc,
491
+ provider=sel_prov_name,
492
+ model_disp_name=sel_model_disp_name,
493
+ insights_reflected=insights_used_parsed,
494
+ api_key_override=ui_api_key.strip() if ui_api_key else None
495
+ )
496
+ status_txt = "Response & Learning Complete."
497
+ except Exception as e_learn:
498
+ logger.error(f"Error during post-interaction learning: {e_learn}", exc_info=True)
499
+ status_txt = "Response complete. Error during learning."
500
+
501
+ elif final_bot_resp_acc.startswith("Error:"):
502
+ status_txt = final_bot_resp_acc
503
+ # If it was an error response from the generator, it's already in updated_gr_hist[-1]
504
+ # The other output components (fmt_report_tb, dl_btn, detect_out_md) are already set by the generator loop or default state
505
+ else:
506
+ status_txt = "Processing finished; no valid response or error occurred during main phase."
507
+
508
+
509
+ # Final yield after learning (or error handling)
510
+ # This final yield updates the UI one last time with the true final status
511
+ # AND crucially refreshes the Rules and Memories displays in case they changed during learning.
512
  updated_rules_text = ui_refresh_rules_display_fn()
513
  updated_mems_json = ui_refresh_memories_display_fn()
514
+
515
  yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn, updated_rules_text, updated_mems_json)
516
+
517
+ # Clean up the temporary download file after the final yield
518
  if temp_dl_file_path and os.path.exists(temp_dl_file_path):
519
  try: os.unlink(temp_dl_file_path)
520
+ except Exception as e_unlink: logger.error(f"Error deleting temp download file {temp_dl_file_path}: {e_unlink}")
521
+
522
+
523
+ # --- Startup Loading Functions ---
524
+ def load_rules_from_file(filepath: str | None):
525
+ """Loads rules from a local file (.txt or .jsonl) and adds them to the system."""
526
+ if not filepath:
527
+ logger.info("LOAD_RULES_FILE environment variable not set. Skipping rules loading from file.")
528
+ return 0, 0, 0 # added, skipped, errors
529
+
530
+ if not os.path.exists(filepath):
531
+ logger.warning(f"LOAD_RULES: Specified rules file not found: {filepath}. Skipping loading.")
532
+ return 0, 0, 0
533
+
534
+ added_count, skipped_count, error_count = 0, 0, 0
535
+ potential_rules = []
536
+
537
+ try:
538
+ with open(filepath, 'r', encoding='utf-8') as f:
539
+ content = f.read()
540
+ except Exception as e:
541
+ logger.error(f"LOAD_RULES: Error reading file {filepath}: {e}", exc_info=False)
542
+ return 0, 0, 1 # Indicate read error
543
+
544
+ if not content.strip():
545
+ logger.info(f"LOAD_RULES: File {filepath} is empty. Skipping loading.")
546
+ return 0, 0, 0
547
+
548
+ file_name_lower = filepath.lower()
549
+
550
+ if file_name_lower.endswith(".txt"):
551
+ potential_rules = content.split("\n\n---\n\n")
552
+ # Also handle simple line breaks if '---' separator is not used
553
+ if len(potential_rules) == 1 and "\n" in content:
554
+ potential_rules = [r.strip() for r in content.splitlines() if r.strip()]
555
+ elif file_name_lower.endswith(".jsonl"):
556
+ for line_num, line in enumerate(content.splitlines()):
557
+ line = line.strip()
558
+ if line:
559
+ try:
560
+ # Expecting each line to be a JSON string containing the rule text
561
+ rule_text_in_json_string = json.loads(line)
562
+ if isinstance(rule_text_in_json_string, str):
563
+ potential_rules.append(rule_text_in_json_string)
564
+ else:
565
+ logger.warning(f"LOAD_RULES (JSONL): Line {line_num+1} in {filepath} did not contain a string value. Got: {type(rule_text_in_json_string)}")
566
+ error_count +=1
567
+ except json.JSONDecodeError:
568
+ logger.warning(f"LOAD_RULES (JSONL): Line {line_num+1} in {filepath} failed to parse as JSON: {line[:100]}")
569
+ error_count +=1
570
+ else:
571
+ logger.error(f"LOAD_RULES: Unsupported file type for rules: {filepath}. Must be .txt or .jsonl")
572
+ return 0, 0, 1 # Indicate type error
573
+
574
+ valid_potential_rules = [r.strip() for r in potential_rules if r.strip()]
575
+ total_to_process = len(valid_potential_rules)
576
+
577
+ if total_to_process == 0 and error_count == 0:
578
+ logger.info(f"LOAD_RULES: No valid rule segments found in {filepath} to process.")
579
+ return 0, 0, 0
580
+ elif total_to_process == 0 and error_count > 0:
581
+ logger.warning(f"LOAD_RULES: No valid rule segments found to process. Encountered {error_count} parsing/format errors in {filepath}.")
582
+ return 0, 0, error_count # Indicate only errors
583
+
584
+ logger.info(f"LOAD_RULES: Attempting to add {total_to_process} potential rules from {filepath}...")
585
+ for idx, rule_text in enumerate(valid_potential_rules):
586
+ success, status_msg = add_rule_entry(rule_text)
587
+ if success:
588
+ added_count += 1
589
+ elif status_msg == "duplicate":
590
+ skipped_count += 1
591
+ else:
592
+ logger.warning(f"LOAD_RULES: Failed to add rule from {filepath} (segment {idx+1}): '{rule_text[:50]}...'. Status: {status_msg}")
593
+ error_count += 1
594
+
595
+ logger.info(f"LOAD_RULES: Finished processing {filepath}. Added: {added_count}, Skipped (duplicates): {skipped_count}, Errors: {error_count}.")
596
+ return added_count, skipped_count, error_count
597
+
598
+ def load_memories_from_file(filepath: str | None):
599
+ """Loads memories from a local file (.json or .jsonl) and adds them to the system."""
600
+ if not filepath:
601
+ logger.info("LOAD_MEMORIES_FILE environment variable not set. Skipping memories loading from file.")
602
+ return 0, 0, 0 # added, format_errors, save_errors
603
+
604
+ if not os.path.exists(filepath):
605
+ logger.warning(f"LOAD_MEMORIES: Specified memories file not found: {filepath}. Skipping loading.")
606
+ return 0, 0, 0
607
+
608
+ added_count, format_error_count, save_error_count = 0, 0, 0
609
+ memory_objects_to_process = []
610
+
611
+ try:
612
+ with open(filepath, 'r', encoding='utf-8') as f:
613
+ content = f.read()
614
+ except Exception as e:
615
+ logger.error(f"LOAD_MEMORIES: Error reading file {filepath}: {e}", exc_info=False)
616
+ return 0, 1, 0 # Indicate read error
617
+
618
+ if not content.strip():
619
+ logger.info(f"LOAD_MEMORIES: File {filepath} is empty. Skipping loading.")
620
+ return 0, 0, 0
621
+
622
+ file_ext = os.path.splitext(filepath.lower())[1]
623
+
624
+ if file_ext == ".json":
625
+ try:
626
+ parsed_json = json.loads(content)
627
+ if isinstance(parsed_json, list):
628
+ memory_objects_to_process = parsed_json
629
+ elif isinstance(parsed_json, dict):
630
+ # If it's a single object, process it as a list of one
631
+ memory_objects_to_process = [parsed_json]
632
+ else:
633
+ logger.warning(f"LOAD_MEMORIES (.json): File content is not a JSON list or object in {filepath}. Type: {type(parsed_json)}")
634
+ format_error_count = 1
635
+ except json.JSONDecodeError as e:
636
+ logger.warning(f"LOAD_MEMORIES (.json): Invalid JSON file {filepath}. Error: {e}")
637
+ format_error_count = 1
638
+ elif file_ext == ".jsonl":
639
+ for line_num, line in enumerate(content.splitlines()):
640
+ line = line.strip()
641
+ if line:
642
+ try:
643
+ memory_objects_to_process.append(json.loads(line))
644
+ except json.JSONDecodeError:
645
+ logger.warning(f"LOAD_MEMORIES (.jsonl): Line {line_num+1} in {filepath} parse error: {line[:100]}")
646
+ format_error_count += 1
647
+ else:
648
+ logger.error(f"LOAD_MEMORIES: Unsupported file type for memories: {filepath}. Must be .json or .jsonl")
649
+ return 0, 1, 0 # Indicate type error
650
+
651
+ total_to_process = len(memory_objects_to_process)
652
+
653
+ if total_to_process == 0 and format_error_count > 0 :
654
+ logger.warning(f"LOAD_MEMORIES: File parsing failed for {filepath}. Found {format_error_count} format errors and no processable objects.")
655
+ return 0, format_error_count, 0
656
+ elif total_to_process == 0:
657
+ logger.info(f"LOAD_MEMORIES: No memory objects found in {filepath} after parsing.")
658
+ return 0, 0, 0
659
+
660
+
661
+ logger.info(f"LOAD_MEMORIES: Attempting to add {total_to_process} memory objects from {filepath}...")
662
+ for idx, mem_data in enumerate(memory_objects_to_process):
663
+ # Validate minimum structure
664
+ if isinstance(mem_data, dict) and all(k in mem_data for k in ["user_input", "bot_response", "metrics"]):
665
+ # Add entry without generating new embeddings if possible (assuming file contains embeddings)
666
+ # NOTE: The current add_memory_entry function *always* generates embeddings.
667
+ # If performance is an issue with large files, memory_logic might need
668
+ # an optimized bulk import function that reuses existing embeddings or
669
+ # generates them in batches. For now, we use the existing function.
670
+ success, _ = add_memory_entry(mem_data["user_input"], mem_data["metrics"], mem_data["bot_response"]) # add_memory_entry needs user_input, metrics, bot_response
671
+ if success:
672
+ added_count += 1
673
+ else:
674
+ # add_memory_entry currently doesn't return detailed error status
675
+ logger.warning(f"LOAD_MEMORIES: Failed to save memory object from {filepath} (segment {idx+1}). Data: {str(mem_data)[:100]}")
676
+ save_error_count += 1
677
+ else:
678
+ logger.warning(f"LOAD_MEMORIES: Skipped invalid memory object structure in {filepath} (segment {idx+1}): {str(mem_data)[:100]}")
679
+ format_error_count += 1
680
+
681
+ logger.info(f"LOAD_MEMORIES: Finished processing {filepath}. Added: {added_count}, Format/Structure Errors: {format_error_count}, Save Errors: {save_error_count}.")
682
+ return added_count, format_error_count, save_error_count
683
+
684
 
685
+ # --- UI Functions for Rules and Memories (ui_refresh_..., ui_download_..., ui_upload_...) ---
686
  def ui_refresh_rules_display_fn(): return "\n\n---\n\n".join(get_all_rules_cached()) or "No rules found."
687
+
688
+ def ui_download_rules_action_fn():
689
+ rules_content = "\n\n---\n\n".join(get_all_rules_cached())
690
+ if not rules_content.strip():
691
+ gr.Warning("No rules to download.")
692
+ return gr.DownloadButton(value=None, interactive=False, label="No Rules")
693
+ try:
694
+ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt", encoding='utf-8') as tmpfile:
695
+ tmpfile.write(rules_content)
696
+ return tmpfile.name
697
+ except Exception as e:
698
+ logger.error(f"Error creating rules download file: {e}")
699
+ gr.Error(f"Failed to prepare rules for download: {e}")
700
+ return gr.DownloadButton(value=None, interactive=False, label="Error")
701
+
702
+ def ui_upload_rules_action_fn(uploaded_file_obj, progress=gr.Progress()):
703
+ if not uploaded_file_obj: return "No file provided for rules upload."
704
+ try:
705
+ with open(uploaded_file_obj.name, 'r', encoding='utf-8') as f: content = f.read()
706
+ except Exception as e_read: return f"Error reading file: {e_read}"
707
+ if not content.strip(): return "Uploaded rules file is empty."
708
+ added_count, skipped_count, error_count = 0,0,0
709
+
710
+ potential_rules = []
711
+ file_name_lower = uploaded_file_obj.name.lower()
712
+
713
+ if file_name_lower.endswith(".txt"):
714
+ potential_rules = content.split("\n\n---\n\n")
715
+ if len(potential_rules) == 1 and "\n" in content:
716
+ potential_rules = [r.strip() for r in content.splitlines() if r.strip()]
717
+ elif file_name_lower.endswith(".jsonl"):
718
+ for line_num, line in enumerate(content.splitlines()):
719
+ line = line.strip()
720
+ if line:
721
+ try:
722
+ rule_text_in_json_string = json.loads(line)
723
+ if isinstance(rule_text_in_json_string, str):
724
+ potential_rules.append(rule_text_in_json_string)
725
+ else:
726
+ logger.warning(f"Rule Upload (JSONL): Line {line_num+1} did not contain a string value. Got: {type(rule_text_in_json_string)}")
727
+ error_count +=1
728
+ except json.JSONDecodeError:
729
+ logger.warning(f"Rule Upload (JSONL): Line {line_num+1} failed to parse as JSON: {line[:100]}")
730
+ error_count +=1
731
+ else:
732
+ return "Unsupported file type for rules. Please use .txt or .jsonl."
733
+
734
+ valid_potential_rules = [r.strip() for r in potential_rules if r.strip()]
735
+ total_to_process = len(valid_potential_rules)
736
+
737
+ if total_to_process == 0 and error_count == 0:
738
+ return "No valid rules found in file to process."
739
+ elif total_to_process == 0 and error_count > 0:
740
+ return f"No valid rules found to process. Encountered {error_count} parsing/format errors."
741
+
742
+ progress(0, desc="Starting rules upload...")
743
+ for idx, rule_text in enumerate(valid_potential_rules):
744
+ success, status_msg = add_rule_entry(rule_text)
745
+ if success: added_count += 1
746
+ elif status_msg == "duplicate": skipped_count += 1
747
+ else: error_count += 1
748
+ progress((idx + 1) / total_to_process, desc=f"Processed {idx+1}/{total_to_process} rules...")
749
+
750
+ msg = f"Rules Upload: Total valid rule segments processed: {total_to_process}. Added: {added_count}, Skipped (duplicates): {skipped_count}, Errors (parsing/add): {error_count}."
751
+ logger.info(msg); return msg
752
+
753
  def ui_refresh_memories_display_fn(): return get_all_memories_cached() or []
754
 
755
+ def ui_download_memories_action_fn():
756
+ memories = get_all_memories_cached()
757
+ if not memories:
758
+ gr.Warning("No memories to download.")
759
+ return gr.DownloadButton(value=None, interactive=False, label="No Memories")
760
+
761
+ jsonl_content = ""
762
+ for mem_dict in memories:
763
+ try: jsonl_content += json.dumps(mem_dict) + "\n"
764
+ except Exception as e: logger.error(f"Error serializing memory for download: {mem_dict}, Error: {e}")
765
+
766
+ if not jsonl_content.strip():
767
+ gr.Warning("No valid memories to serialize for download.")
768
+ return gr.DownloadButton(value=None, interactive=False, label="No Data")
769
+ try:
770
+ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".jsonl", encoding='utf-8') as tmpfile:
771
+ tmpfile.write(jsonl_content)
772
+ return tmpfile.name
773
+ except Exception as e:
774
+ logger.error(f"Error creating memories download file: {e}")
775
+ gr.Error(f"Failed to prepare memories for download: {e}")
776
+ return gr.DownloadButton(value=None, interactive=False, label="Error")
777
+
778
+ def ui_upload_memories_action_fn(uploaded_file_obj, progress=gr.Progress()):
779
+ if not uploaded_file_obj: return "No file provided for memories upload."
780
+ try:
781
+ with open(uploaded_file_obj.name, 'r', encoding='utf-8') as f: content = f.read()
782
+ except Exception as e_read: return f"Error reading file: {e_read}"
783
+ if not content.strip(): return "Uploaded memories file is empty."
784
+ added_count, format_error_count, save_error_count = 0,0,0
785
+ memory_objects_to_process = []
786
+
787
+ file_ext = os.path.splitext(uploaded_file_obj.name.lower())[1]
788
+
789
+ if file_ext == ".json":
790
+ try:
791
+ parsed_json = json.loads(content)
792
+ if isinstance(parsed_json, list):
793
+ memory_objects_to_process = parsed_json
794
+ elif isinstance(parsed_json, dict):
795
+ memory_objects_to_process = [parsed_json]
796
+ else:
797
+ logger.warning(f"Memories Upload (.json): File content is not a JSON list or object. Type: {type(parsed_json)}")
798
+ format_error_count = 1
799
+ except json.JSONDecodeError as e:
800
+ logger.warning(f"Memories Upload (.json): Invalid JSON file. Error: {e}")
801
+ format_error_count = 1
802
+ elif file_ext == ".jsonl":
803
+ for line_num, line in enumerate(content.splitlines()):
804
+ line = line.strip()
805
+ if line:
806
+ try:
807
+ memory_objects_to_process.append(json.loads(line))
808
+ except json.JSONDecodeError:
809
+ logger.warning(f"Memories Upload (.jsonl): Line {line_num+1} parse error: {line[:100]}")
810
+ format_error_count += 1
811
+ else:
812
+ return "Unsupported file type for memories. Please use .json or .jsonl."
813
+
814
+ if not memory_objects_to_process and format_error_count > 0 :
815
+ return f"Memories Upload: File parsing failed. Found {format_error_count} format errors and no processable objects."
816
+ elif not memory_objects_to_process:
817
+ return "No valid memory objects found in the uploaded file."
818
+
819
+ total_to_process = len(memory_objects_to_process)
820
+ if total_to_process == 0: return "No memory objects to process (after parsing)."
821
+
822
+ progress(0, desc="Starting memories upload...")
823
+ for idx, mem_data in enumerate(memory_objects_to_process):
824
+ if isinstance(mem_data, dict) and all(k in mem_data for k in ["user_input", "bot_response", "metrics"]):
825
+ success, _ = add_memory_entry(mem_data["user_input"], mem_data["metrics"], mem_data["bot_response"])
826
+ if success: added_count += 1
827
+ else: save_error_count += 1
828
+ else:
829
+ logger.warning(f"Memories Upload: Skipped invalid memory object structure: {str(mem_data)[:100]}")
830
+ format_error_count += 1
831
+ progress((idx + 1) / total_to_process, desc=f"Processed {idx+1}/{total_to_process} memories...")
832
+
833
+ msg = f"Memories Upload: Processed {total_to_process} objects. Added: {added_count}, Format/Structure Errors: {format_error_count}, Save Errors: {save_error_count}."
834
+ logger.info(msg); return msg
835
+
836
+ def save_edited_rules_action_fn(edited_rules_text: str, progress=gr.Progress()):
837
+ if not edited_rules_text.strip():
838
+ return "No rules text to save."
839
+
840
+ potential_rules = edited_rules_text.split("\n\n---\n\n")
841
+ if len(potential_rules) == 1 and "\n" in edited_rules_text:
842
+ potential_rules = [r.strip() for r in edited_rules_text.splitlines() if r.strip()]
843
+
844
+ if not potential_rules:
845
+ return "No rules found to process from editor."
846
+
847
+ added, skipped, errors = 0, 0, 0
848
+ unique_rules_to_process = sorted(list(set(filter(None, [r.strip() for r in potential_rules]))))
849
+
850
+ total_unique = len(unique_rules_to_process)
851
+ if total_unique == 0: return "No unique, non-empty rules found in editor text."
852
+
853
+ progress(0, desc=f"Saving {total_unique} unique rules from editor...")
854
+
855
+ for idx, rule_text in enumerate(unique_rules_to_process):
856
+ success, status_msg = add_rule_entry(rule_text)
857
+ if success: added += 1
858
+ elif status_msg == "duplicate": skipped += 1
859
+ else: errors += 1
860
+ progress((idx + 1) / total_unique, desc=f"Processed {idx+1}/{total_unique} rules...")
861
+
862
+ return f"Editor Save: Added: {added}, Skipped (duplicates): {skipped}, Errors/Invalid: {errors} from {total_unique} unique rules in text."
863
+
864
  def app_load_fn():
865
+ logger.info("App loading. Initializing systems...")
866
  initialize_memory_system()
867
+ logger.info("Memory system initialized.")
868
+
869
+ # --- Load Rules from File ---
870
+ rules_added, rules_skipped, rules_errors = load_rules_from_file(LOAD_RULES_FILE)
871
+ rules_load_msg = f"Rules: Added {rules_added}, Skipped {rules_skipped}, Errors {rules_errors} from {LOAD_RULES_FILE or 'None'}."
872
+ logger.info(rules_load_msg)
873
+
874
+ # --- Load Memories from File ---
875
+ mems_added, mems_format_errors, mems_save_errors = load_memories_from_file(LOAD_MEMORIES_FILE)
876
+ mems_load_msg = f"Memories: Added {mems_added}, Format Errors {mems_format_errors}, Save Errors {mems_save_errors} from {LOAD_MEMORIES_FILE or 'None'}."
877
+ logger.info(mems_load_msg)
878
+
879
+ final_status = f"AI Systems Initialized. {rules_load_msg} {mems_load_msg} Ready."
880
+
881
+ # Initial population of all relevant UI components AFTER loading
882
+ rules_on_load = ui_refresh_rules_display_fn()
883
+ mems_on_load = ui_refresh_memories_display_fn()
884
+
885
+ # Return values for outputs defined in demo.load
886
+ return (
887
+ final_status, # agent_stat_tb
888
+ rules_on_load, # rules_disp_ta
889
+ mems_on_load, # mems_disp_json
890
+ gr.Markdown(visible=False), # detect_out_md (initial state)
891
+ gr.Textbox(value="*Waiting...*", interactive=True, show_copy_button=True), # fmt_report_tb (initial state)
892
+ gr.DownloadButton(interactive=False, value=None, visible=False), # dl_report_btn (initial state)
893
+ )
894
+
895
+
896
+ # --- Gradio UI Definition ---
897
+ with gr.Blocks(
898
+ theme=gr.themes.Soft(),
899
+ css="""
900
+ .gr-button { margin: 5px; }
901
+ .gr-textbox, .gr-text-area, .gr-dropdown, .gr-json { border-radius: 8px; }
902
+ .gr-group { border: 1px solid #e0e0e0; border-radius: 8px; padding: 10px; }
903
+ .gr-row { gap: 10px; }
904
+ .gr-tab { border-radius: 8px; }
905
+ .status-text { font-size: 0.9em; color: #555; }
906
+ .gr-json { max-height: 300px; overflow-y: auto; } /* Added scrolling for JSON */
907
+ """
908
+ ) as demo:
909
+ gr.Markdown(
910
+ """
911
+ # πŸ€– AI Research Agent
912
+ Your intelligent assistant for research and knowledge management
913
+ """,
914
+ elem_classes=["header"]
915
+ )
916
+
917
+ is_sqlite = MEMORY_STORAGE_BACKEND == "SQLITE"
918
+ is_hf_dataset = MEMORY_STORAGE_BACKEND == "HF_DATASET"
919
 
 
 
920
  with gr.Row(variant="compact"):
921
+ agent_stat_tb = gr.Textbox(
922
+ label="Agent Status", value="Initializing systems...", interactive=False,
923
+ elem_classes=["status-text"], scale=4
924
+ )
925
  with gr.Column(scale=1, min_width=150):
926
+ memory_backend_info_tb = gr.Textbox(
927
+ label="Memory Backend", value=MEMORY_STORAGE_BACKEND, interactive=False,
928
+ elem_classes=["status-text"]
929
+ )
930
+ sqlite_path_display = gr.Textbox(
931
+ label="SQLite Path", value=MEMORY_SQLITE_PATH, interactive=False,
932
+ visible=is_sqlite, elem_classes=["status-text"]
933
+ )
934
+ hf_repos_display = gr.Textbox(
935
+ label="HF Repos", value=f"M: {MEMORY_HF_MEM_REPO}, R: {MEMORY_HF_RULES_REPO}",
936
+ interactive=False, visible=is_hf_dataset, elem_classes=["status-text"]
937
+ )
938
+
939
  with gr.Row():
940
  with gr.Sidebar():
941
  gr.Markdown("## βš™οΈ Configuration")
942
+ with gr.Group():
943
+ gr.Markdown("### AI Model Settings")
944
+ api_key_tb = gr.Textbox(
945
+ label="AI Provider API Key (Override)", type="password", placeholder="Uses .env if blank"
946
+ )
947
+ available_providers = get_available_providers()
948
+ default_provider = available_providers[0] if available_providers else None
949
+ prov_sel_dd = gr.Dropdown(
950
+ label="AI Provider", choices=available_providers,
951
+ value=default_provider, interactive=True
952
+ )
953
+ default_model_display = get_default_model_display_name_for_provider(default_provider) if default_provider else None
954
+ model_sel_dd = gr.Dropdown(
955
+ label="AI Model",
956
+ choices=get_model_display_names_for_provider(default_provider) if default_provider else [],
957
+ value=default_model_display,
958
+ interactive=True
959
+ )
960
+ with gr.Group():
961
+ gr.Markdown("### System Prompt")
962
+ sys_prompt_tb = gr.Textbox(
963
+ label="System Prompt Base", lines=8, value=DEFAULT_SYSTEM_PROMPT, interactive=True
964
+ )
965
+ if MEMORY_STORAGE_BACKEND == "RAM":
966
+ save_faiss_sidebar_btn = gr.Button("Save FAISS Indices", variant="secondary")
967
+
968
  with gr.Column(scale=3):
969
  with gr.Tabs():
970
  with gr.TabItem("πŸ’¬ Chat & Research"):
971
+ with gr.Group():
972
+ gr.Markdown("### AI Chat Interface")
973
+ main_chat_disp = gr.Chatbot(
974
+ label=None, height=400, bubble_full_width=False,
975
+ avatar_images=(None, "https://raw.githubusercontent.com/huggingface/brand-assets/main/hf-logo-with-title.png"),
976
+ show_copy_button=True, render_markdown=True, sanitize_html=True
977
+ )
978
+ with gr.Row(variant="compact"):
979
+ user_msg_tb = gr.Textbox(
980
+ show_label=False, placeholder="Ask your research question...",
981
+ scale=7, lines=1, max_lines=3
982
+ )
983
+ send_btn = gr.Button("Send", variant="primary", scale=1, min_width=100)
984
+ with gr.Accordion("πŸ“ Detailed Response & Insights", open=False):
985
+ fmt_report_tb = gr.Textbox(
986
+ label="Full AI Response", lines=8, interactive=True, show_copy_button=True
987
+ )
988
+ dl_report_btn = gr.DownloadButton(
989
+ "Download Report", value=None, interactive=False, visible=False
990
+ )
991
+ detect_out_md = gr.Markdown(visible=False)
992
+
993
  with gr.TabItem("🧠 Knowledge Base"):
994
+ with gr.Row(equal_height=True):
995
  with gr.Column():
996
+ gr.Markdown("### πŸ“œ Rules Management")
997
+ rules_disp_ta = gr.TextArea(
998
+ label="Current Rules", lines=10,
999
+ placeholder="Rules will appear here.",
1000
+ interactive=True
1001
+ )
1002
+ gr.Markdown("To edit rules, modify the text above and click 'Save Edited Text', or upload a new file.")
1003
  save_edited_rules_btn = gr.Button("πŸ’Ύ Save Edited Text", variant="primary")
1004
+ with gr.Row(variant="compact"):
1005
+ dl_rules_btn = gr.DownloadButton("⬇️ Download Rules", value=None)
1006
+ clear_rules_btn = gr.Button("πŸ—‘οΈ Clear All Rules", variant="stop")
1007
+ upload_rules_fobj = gr.File(
1008
+ label="Upload Rules File (.txt with '---' separators, or .jsonl of rule strings)",
1009
+ file_types=[".txt", ".jsonl"]
1010
+ )
1011
+ rules_stat_tb = gr.Textbox(
1012
+ label="Rules Status", interactive=False, lines=1, elem_classes=["status-text"]
1013
+ )
1014
+
1015
  with gr.Column():
1016
+ gr.Markdown("### πŸ“š Memories Management")
1017
+ mems_disp_json = gr.JSON(
1018
+ label="Current Memories", value=[]
1019
+ )
1020
+ gr.Markdown("To add memories, upload a .jsonl or .json file.")
1021
+ with gr.Row(variant="compact"):
1022
+ dl_mems_btn = gr.DownloadButton("⬇️ Download Memories", value=None)
1023
+ clear_mems_btn = gr.Button("πŸ—‘οΈ Clear All Memories", variant="stop")
1024
+ upload_mems_fobj = gr.File(
1025
+ label="Upload Memories File (.jsonl of memory objects, or .json array of objects)",
1026
+ file_types=[".jsonl", ".json"]
1027
+ )
1028
+ mems_stat_tb = gr.Textbox(
1029
+ label="Memories Status", interactive=False, lines=1, elem_classes=["status-text"]
1030
+ )
1031
 
1032
  def dyn_upd_model_dd(sel_prov_dyn: str):
1033
+ models_dyn = get_model_display_names_for_provider(sel_prov_dyn)
1034
+ def_model_dyn = get_default_model_display_name_for_provider(sel_prov_dyn)
1035
+ return gr.Dropdown(choices=models_dyn, value=def_model_dyn, interactive=True)
1036
+
1037
  prov_sel_dd.change(fn=dyn_upd_model_dd, inputs=prov_sel_dd, outputs=model_sel_dd)
1038
 
1039
+ # Inputs for the main chat submission function
1040
  chat_ins = [user_msg_tb, main_chat_disp, prov_sel_dd, model_sel_dd, api_key_tb, sys_prompt_tb]
1041
+ # Outputs for the main chat submission function (includes knowledge base displays)
1042
  chat_outs = [user_msg_tb, main_chat_disp, agent_stat_tb, detect_out_md, fmt_report_tb, dl_report_btn, rules_disp_ta, mems_disp_json]
1043
+
1044
+ chat_event_args = {"fn": handle_gradio_chat_submit, "inputs": chat_ins, "outputs": chat_outs}
1045
+
1046
+ send_btn.click(**chat_event_args)
1047
+ user_msg_tb.submit(**chat_event_args)
1048
+
1049
+ # Rules Management events
1050
+ dl_rules_btn.click(fn=ui_download_rules_action_fn, inputs=None, outputs=dl_rules_btn, show_progress=False) # show_progress=False for download buttons
1051
+
1052
+ save_edited_rules_btn.click(
1053
+ fn=save_edited_rules_action_fn,
1054
+ inputs=[rules_disp_ta],
1055
+ outputs=[rules_stat_tb],
1056
+ show_progress="full"
1057
+ ).then(fn=ui_refresh_rules_display_fn, outputs=rules_disp_ta, show_progress=False) # Refresh display after saving
1058
+
1059
+ upload_rules_fobj.upload(
1060
+ fn=ui_upload_rules_action_fn,
1061
+ inputs=[upload_rules_fobj],
1062
+ outputs=[rules_stat_tb],
1063
+ show_progress="full"
1064
+ ).then(fn=ui_refresh_rules_display_fn, outputs=rules_disp_ta, show_progress=False) # Refresh display after upload
1065
+
1066
+ clear_rules_btn.click(
1067
+ fn=lambda: ("All rules cleared." if clear_all_rules_data_backend() else "Error clearing rules."),
1068
+ outputs=rules_stat_tb,
1069
+ show_progress=False
1070
+ ).then(fn=ui_refresh_rules_display_fn, outputs=rules_disp_ta, show_progress=False) # Refresh display after clear
1071
+
1072
+ # Memories Management events
1073
+ dl_mems_btn.click(fn=ui_download_memories_action_fn, inputs=None, outputs=dl_mems_btn, show_progress=False) # show_progress=False for download buttons
1074
+
1075
+ upload_mems_fobj.upload(
1076
+ fn=ui_upload_memories_action_fn,
1077
+ inputs=[upload_mems_fobj],
1078
+ outputs=[mems_stat_tb],
1079
+ show_progress="full"
1080
+ ).then(fn=ui_refresh_memories_display_fn, outputs=mems_disp_json, show_progress=False) # Refresh display after upload
1081
+
1082
+ clear_mems_btn.click(
1083
+ fn=lambda: ("All memories cleared." if clear_all_memory_data_backend() else "Error clearing memories."),
1084
+ outputs=mems_stat_tb,
1085
+ show_progress=False
1086
+ ).then(fn=ui_refresh_memories_display_fn, outputs=mems_disp_json, show_progress=False) # Refresh display after clear
1087
+
1088
+ # FAISS save button visibility and action (RAM backend only)
1089
+ if MEMORY_STORAGE_BACKEND == "RAM" and 'save_faiss_sidebar_btn' in locals():
1090
+ def save_faiss_action_with_feedback_sidebar_fn():
1091
+ try:
1092
+ save_faiss_indices_to_disk()
1093
+ gr.Info("Attempted to save FAISS indices to disk.")
1094
+ except Exception as e:
1095
+ logger.error(f"Error saving FAISS indices: {e}", exc_info=True)
1096
+ gr.Error(f"Error saving FAISS indices: {e}")
1097
+
1098
+ save_faiss_sidebar_btn.click(fn=save_faiss_action_with_feedback_sidebar_fn, inputs=None, outputs=None, show_progress=False)
1099
+
1100
+
1101
+ # --- Initial Load Event ---
1102
+ # This function runs once when the Gradio app starts.
1103
+ # It initializes the memory system and loads data from specified files.
1104
+ # Its outputs populate the initial state of several UI components.
1105
+ app_load_outputs = [
1106
+ agent_stat_tb, # Updates status text
1107
+ rules_disp_ta, # Populates rules display
1108
+ mems_disp_json, # Populates memories display
1109
+ detect_out_md, # Sets initial visibility/value for insights markdown
1110
+ fmt_report_tb, # Sets initial value for detailed response textbox
1111
+ dl_report_btn # Sets initial state for download button
1112
+ ]
1113
+ demo.load(fn=app_load_fn, inputs=None, outputs=app_load_outputs, show_progress="full")
1114
+
1115
 
1116
  if __name__ == "__main__":
1117
+ logger.info(f"Starting Gradio AI Research Mega Agent (v6.5 - Direct UI Update & Core Learning Memories, Memory: {MEMORY_STORAGE_BACKEND})...")
1118
  app_port = int(os.getenv("GRADIO_PORT", 7860))
1119
  app_server = os.getenv("GRADIO_SERVER_NAME", "127.0.0.1")
1120
+ app_debug = os.getenv("GRADIO_DEBUG", "False").lower() == "true"
1121
+ app_share = os.getenv("GRADIO_SHARE", "False").lower() == "true"
1122
+ logger.info(f"Launching Gradio server: http://{app_server}:{app_port}. Debug: {app_debug}, Share: {app_share}")
1123
+ demo.queue().launch(server_name=app_server, server_port=app_port, debug=app_debug, share=app_share)
1124
+ logger.info("Gradio application shut down.")