broadfield-dev commited on
Commit
29f7fc8
·
verified ·
1 Parent(s): 187bd4b

Create app.py

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