broadfield-dev commited on
Commit
e7a6f78
·
verified ·
1 Parent(s): ef71876

Update app.py

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