broadfield-dev commited on
Commit
d17fb14
Β·
verified Β·
1 Parent(s): f531178

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +459 -186
app.py CHANGED
@@ -1,223 +1,497 @@
1
  # app.py
2
- # ... (all other Python code remains the same) ...
 
 
 
 
 
 
 
 
 
3
 
4
- custom_theme = gr.themes.Base(primary_hue="teal", secondary_hue="purple", neutral_hue="zinc", text_size="sm", spacing_size="md", radius_size="sm", font=["System UI", "sans-serif"])
5
- custom_css = """
6
- html, body { /* Reset browser defaults for html and body */
7
- margin: 0 !important;
8
- padding: 0 !important;
9
- height: 100%; /* Ensure body can fill height if needed */
10
- box-sizing: border-box; /* Better box model */
11
- }
12
- *, *:before, *:after { /* Apply box-sizing to all elements */
13
- box-sizing: inherit;
14
- }
15
 
16
- body {
17
- background: linear-gradient(to bottom right, #2c3e50, #34495e);
18
- color: #ecf0f1;
19
- min-height: 100vh; /* Ensure body takes at least full viewport height */
20
- font-family: 'Inter', sans-serif; /* Moved font-family here for global effect */
21
- }
 
 
 
 
 
 
22
 
23
- .gradio-container {
24
- background: transparent !important;
25
- max-width: 100% !important; /* Use 100% to avoid slight gaps on sides sometimes seen with 98/96% */
26
- padding: 1rem !important; /* Ensure some padding around the content */
27
- margin: 0 auto !important; /* Center if max-width was less than 100% */
28
- min-height: 100vh; /* Make container also try to fill height */
29
- display: flex; /* Helps with some layout consistencies */
30
- flex-direction: column; /* Stack children vertically */
31
- }
32
 
33
- /* Target the very first direct child block of gradio-container to remove top margin if any */
34
- .gradio-container > .gr-block:first-child {
35
- margin-top: 0 !important;
36
- }
 
37
 
38
- /* Target the main title markdown specifically if it's causing issues */
39
- .gradio-container > .gr-block.gr-markdown:first-child h1:first-child {
40
- margin-top: 0 !important;
41
- padding-top: 0 !important; /* Also try padding */
42
- }
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
- .gr-box, .gr-panel, .gr-tabs, .gr-accordion {
46
- background-color: rgba(44, 62, 80, 0.85) !important;
47
- border: 1px solid rgba(189, 195, 199, 0.2) !important;
48
- border-radius: 8px !important;
49
- box-shadow: 0 4px 6px rgba(0,0,0,0.1);
50
- }
51
- .gr-tabitem {
52
- background-color: rgba(52, 73, 94, 0.7) !important;
53
- border-radius: 6px !important;
54
- margin-bottom: 5px !important;
55
- padding: 1em !important;
56
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- .gr-textbox, .gr-dropdown, .gr-button, .gr-code, .gr-chat-message, .gr-json, .gr-file input[type="file"] {
59
- border: 1px solid rgba(189, 195, 199, 0.3) !important;
60
- background-color: rgba(52, 73, 94, 0.9) !important;
61
- color: #ecf0f1 !important;
62
- border-radius: 6px !important;
63
- }
64
- .gr-file {
65
- background-color: rgba(52, 73, 94, 0.9) !important;
66
- border-radius: 6px !important; padding: 0.5em;
67
- }
68
- .gr-file > .label-text { color: #bdc3c7 !important;}
69
- .gr-textarea textarea, .gr-textbox input { color: #ecf0f1 !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
- .gr-button.gr-button-primary { background-color: #1abc9c !important; color: white !important; border-color: #16a085 !important; }
72
- .gr-button.gr-button-secondary { background-color: #9b59b6 !important; color: white !important; border-color: #8e44ad !important; }
73
- .gr-button.gr-button-stop { background-color: #e74c3c !important; color: white !important; border-color: #c0392b !important; }
 
 
 
 
 
 
 
74
 
75
- .gr-markdown { background-color: transparent !important; padding: 0px; } /* Make markdown itself transparent if inside a styled box */
76
- .gr-markdown h1, .gr-markdown h2, .gr-markdown h3 {
77
- color: #1abc9c !important;
78
- border-bottom: 1px solid rgba(189, 195, 199, 0.2) !important;
79
- padding-bottom: 0.3em;
80
- margin-top: 0.8em; /* Adjust default top margin for headers within markdown */
81
- margin-bottom: 0.5em;
82
- }
83
- .gr-markdown p, .gr-markdown li { color: #ecf0f1 !important; }
84
- .gr-markdown pre code {
85
- background-color: rgba(30, 40, 50, 0.95) !important;
86
- border: 1px solid rgba(189, 195, 199, 0.3) !important;
87
- color: #ecf0f1;
88
- border-radius: 4px; padding: 0.8em;
89
- }
90
 
91
- .gr-chatbot {
92
- background-color: rgba(44, 62, 80, 0.7) !important;
93
- border: 1px solid rgba(189, 195, 199, 0.2) !important;
94
- }
95
- .gr-chatbot .message {
96
- background-color: rgba(52, 73, 94, 0.9) !important;
97
- color: #ecf0f1 !important;
98
- border: 1px solid rgba(189, 195, 199, 0.2) !important;
99
- box-shadow: 0 1px 2px rgba(0,0,0,0.1) !important;
100
- }
101
- .gr-chatbot .message.user {
102
- background-color: rgba(46, 204, 113, 0.8) !important;
103
- color: #2c3e50 !important;
104
- }
105
 
106
- .gr-input-label > .label-text, .gr-dropdown-label > .label-text, .gr-checkbox-label > .label-text {
107
- color: #bdc3c7 !important;
108
- font-size: 0.9rem !important;
109
- }
110
- .gr-info { color: #bdc3c7 !important; font-size: 0.85rem !important; }
 
 
111
 
112
- #status_bar_group { /* Renamed from elem_id to elem_classes if Gradio prefers that for styling groups */
113
- background-color: rgba(44, 62, 80, 0.8) !important;
114
- padding: 8px;
115
- border-radius: 6px;
116
- margin-bottom: 10px;
117
- }
118
- /* If using elem_classes="status-bar-group" on the gr.Row instead of elem_id */
119
- .status-bar-group {
120
- background-color: rgba(44, 62, 80, 0.8) !important;
121
- padding: 8px;
122
- border-radius: 6px;
123
- margin-bottom: 10px;
124
- }
 
 
125
 
 
 
 
 
126
 
127
- .tabnav button { /* Style for tab buttons */
128
- background-color: rgba(52, 73, 94, 0.8) !important;
129
- color: #ecf0f1 !important;
130
- border-bottom: 2px solid transparent !important;
131
- border-top-left-radius: 6px !important; /* Slightly rounded top corners */
132
- border-top-right-radius: 6px !important;
133
- margin-right: 2px !important; /* Small gap between tab buttons */
134
- }
135
- .tabnav button.selected {
136
- background-color: rgba(44, 62, 80, 0.95) !important; /* Match tab content background */
137
- color: #1abc9c !important;
138
- border-bottom: 2px solid #1abc9c !important;
139
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
 
141
- .gr-block.gr-box { padding: 1em; } /* General padding for groups/boxes */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
- /* Ensure the main title Markdown doesn't have excessive top margin */
144
- .gradio-container > .gr-block.gr-markdown:first-of-type h1 {
145
- margin-top: 0 !important; /* This is more specific */
146
- }
147
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
- # The rest of your app.py (Python code for functions, UI layout, event handlers)
150
- # ...
151
- # Ensure the gr.Blocks() call doesn't have `fill_height=True` if it causes issues,
152
- # or if it does, make sure parent elements are also set up for flexible height.
153
- # The `min-height: 100vh` on body and .gradio-container is usually sufficient.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
  with gr.Blocks(theme=custom_theme, css=custom_css, title="AI Research Mega Agent v5.3") as demo:
156
- gr.Markdown("# πŸš€ AI Research Mega Agent Dashboard") # This is the first visible element
157
 
158
  avail_provs = get_available_providers()
159
  def_prov = avail_provs[0] if avail_provs else None
160
  def_models = get_model_display_names_for_provider(def_prov) if def_prov else []
161
  def_model_disp = get_default_model_display_name_for_provider(def_prov) if def_prov else None
162
 
163
- # Moved status bar below the main title for better flow
164
- with gr.Row(elem_classes="status-bar-group"): # Use elem_classes for easier targeting
165
  with gr.Column(scale=3): agent_stat_tb = gr.Textbox(label="Agent Status", interactive=False, lines=1, value="Initializing systems...")
166
  with gr.Column(scale=1): memory_backend_info_tb = gr.Textbox(label="Memory Backend", value=f"{MEMORY_STORAGE_BACKEND}", interactive=False)
167
  if MEMORY_STORAGE_BACKEND == "SQLITE":
168
- with gr.Column(scale=2): gr.Textbox(label="SQLite Path", value=f"{MEMORY_SQLITE_PATH}", interactive=False, elem_id="sqlite_path_display") # Added elem_id for potential specific styling
169
  elif MEMORY_STORAGE_BACKEND == "HF_DATASET":
170
- with gr.Column(scale=2): gr.Textbox(label="HF Repos", value=f"M: {MEMORY_HF_MEM_REPO}, R: {MEMORY_HF_RULES_REPO}", interactive=False, elem_id="hf_repos_display")
171
-
172
- with gr.Tabs() as main_tabs:
173
- with gr.TabItem("βš™οΈ Agent Configuration & πŸ’¬ Chat", id=0): # Combined Config and Chat
174
- with gr.Row(equal_height=False): # Allow columns to size independently
175
- with gr.Column(scale=1, min_width=380): # Sidebar for config
176
- gr.Markdown("## βš™οΈ LLM Configuration")
177
- with gr.Group(): # Removed elem_classes="compact-group" unless specifically needed for sub-styling
178
- prov_sel_dd = gr.Dropdown(label="AI Provider", choices=avail_provs, value=def_prov, interactive=True)
179
- model_sel_dd = gr.Dropdown(label="AI Model", choices=def_models, value=def_model_disp, interactive=True)
180
- api_key_tb = gr.Textbox(label="API Key Override (Optional)", type="password", placeholder="Paste key for selected provider")
181
- with gr.Group():
182
- sys_prompt_tb = gr.Textbox(label="System Prompt Base", lines=10, value=DEFAULT_SYSTEM_PROMPT, interactive=True)
183
-
184
- with gr.Column(scale=2): # Main chat area
 
 
185
  gr.Markdown("## πŸ’¬ AI Chat Interface")
186
  main_chat_disp = gr.Chatbot(label="AI Research Chat", height=550, bubble_full_width=False, avatar_images=(None, "https://raw.githubusercontent.com/huggingface/brand-assets/main/hf-logo-with-title.png"), show_copy_button=True, render_markdown=True, sanitize_html=True)
187
  with gr.Row():
188
  user_msg_tb = gr.Textbox(show_label=False, placeholder="Ask your research question or give an instruction...", scale=7, lines=1, max_lines=5, autofocus=True)
189
  send_btn = gr.Button("Send", variant="primary", scale=1, min_width=100)
190
-
191
- with gr.Accordion("πŸ“ Full Response / Output Details", open=False): # Initially closed
192
- fmt_report_tb = gr.Textbox(label="Full AI Response", lines=10, interactive=True, show_copy_button=True, value="*AI responses will appear here...*")
193
- dl_report_btn = gr.DownloadButton("Download Report", interactive=False, visible=False)
194
- detect_out_md = gr.Markdown("*Insights used or other intermediate details will show here...*")
195
 
196
- with gr.TabItem("🧠 Knowledge Base Management", id=1):
197
- gr.Markdown("## Manage Stored Knowledge") # Top level header for the tab
198
- with gr.Row(equal_height=False):
199
- with gr.Column(scale=1):
200
- with gr.Box(): # Using Box for a slightly more contained look
201
- gr.Markdown("### πŸ“œ Rules (Learned Insights)")
202
- rules_disp_ta = gr.TextArea(label="View/Edit Rules", lines=15, interactive=True, placeholder="Load or type rules here (one per line or '---' separated for multiple).")
203
- with gr.Row():
204
- view_rules_btn = gr.Button("πŸ”„ Load/Refresh Rules View"); save_edited_rules_btn = gr.Button("πŸ’Ύ Save Edited Rules", variant="primary")
205
- upload_rules_fobj = gr.File(label="Upload Rules File (.txt/.jsonl)", file_types=[".txt", ".jsonl"])
206
- rules_stat_tb = gr.Textbox(label="Rules Operation Status", interactive=False, lines=2, placeholder="Status of rule operations...")
207
- with gr.Row():
208
- clear_rules_btn = gr.Button("⚠️ Clear All Rules", variant="stop")
209
- save_faiss_ram_btn_kb = gr.Button("Save FAISS Indices", visible=(MEMORY_STORAGE_BACKEND == "RAM"))
210
-
211
- with gr.Column(scale=1):
212
- with gr.Box():
213
- gr.Markdown("### πŸ“š Memories (Past Interactions)")
214
- mems_disp_json = gr.JSON(label="View Memories (JSON format)", scale=2)
215
- with gr.Row(): view_mems_btn = gr.Button("πŸ”„ Load/Refresh Memories View")
216
- upload_mems_fobj = gr.File(label="Upload Memories File (.jsonl)", file_types=[".jsonl"])
217
- mems_stat_tb = gr.Textbox(label="Memories Operation Status", interactive=False, lines=2, placeholder="Status of memory operations...")
218
- clear_mems_btn = gr.Button("⚠️ Clear All Memories", variant="stop")
219
 
220
- # --- Event Handlers (remain the same as your last correct version) ---
221
  def dyn_upd_model_dd(sel_prov_dyn:str): models_dyn, def_model_dyn = get_model_display_names_for_provider(sel_prov_dyn), get_default_model_display_name_for_provider(sel_prov_dyn); return gr.Dropdown(choices=models_dyn, value=def_model_dyn, interactive=True)
222
  prov_sel_dd.change(fn=dyn_upd_model_dd, inputs=prov_sel_dd, outputs=model_sel_dd)
223
  chat_ins = [user_msg_tb, main_chat_disp, prov_sel_dd, model_sel_dd, api_key_tb, sys_prompt_tb]
@@ -245,7 +519,7 @@ with gr.Blocks(theme=custom_theme, css=custom_css, title="AI Research Mega Agent
245
  upload_rules_fobj.upload(fn=ui_upload_rules_action_fn, inputs=[upload_rules_fobj], outputs=[rules_stat_tb], show_progress="full").then(fn=ui_view_rules_action_fn, outputs=rules_disp_ta)
246
  clear_rules_btn.click(fn=lambda: "All rules cleared." if clear_all_rules_data_backend() else "Error clearing rules.", outputs=rules_stat_tb).then(fn=ui_view_rules_action_fn, outputs=rules_disp_ta)
247
 
248
- if MEMORY_STORAGE_BACKEND == "RAM" and save_faiss_ram_btn_kb is not None:
249
  def save_faiss_action_with_feedback_fn_kb(): save_faiss_indices_to_disk(); gr.Info("Attempted to save FAISS indices to disk.")
250
  save_faiss_ram_btn_kb.click(fn=save_faiss_action_with_feedback_fn_kb, inputs=None, outputs=None)
251
 
@@ -263,11 +537,10 @@ with gr.Blocks(theme=custom_theme, css=custom_css, title="AI Research Mega Agent
263
 
264
  demo.load(fn=app_load_fn, inputs=None, outputs=[agent_stat_tb, rules_disp_ta, mems_disp_json])
265
 
266
-
267
  if __name__ == "__main__":
268
- logger.info(f"Starting Gradio AI Research Mega Agent (v5.3 with UI fixes & Advanced Memory: {MEMORY_STORAGE_BACKEND})...")
269
  app_port, app_server = int(os.getenv("GRADIO_PORT", 7860)), os.getenv("GRADIO_SERVER_NAME", "127.0.0.1")
270
  app_debug, app_share = os.getenv("GRADIO_DEBUG", "False").lower()=="true", os.getenv("GRADIO_SHARE", "False").lower()=="true"
271
  logger.info(f"Launching Gradio server: http://{app_server}:{app_port}. Debug: {app_debug}, Share: {app_share}")
272
- demo.queue().launch(server_name=app_server, server_port=app_port, debug=app_debug, share=app_share) # fill_height might not be needed with body/container min-height
273
  logger.info("Gradio application shut down.")
 
1
  # app.py
2
+ import os
3
+ import json
4
+ import re
5
+ import logging
6
+ import threading
7
+ from datetime import datetime
8
+ from dotenv import load_dotenv
9
+ import gradio as gr
10
+ import time
11
+ import tempfile
12
 
13
+ load_dotenv()
 
 
 
 
 
 
 
 
 
 
14
 
15
+ from model_logic import (
16
+ get_available_providers, get_model_display_names_for_provider,
17
+ get_default_model_display_name_for_provider, call_model_stream, MODELS_BY_PROVIDER
18
+ )
19
+ from memory_logic import (
20
+ initialize_memory_system,
21
+ add_memory_entry, retrieve_memories_semantic, get_all_memories_cached, clear_all_memory_data_backend,
22
+ add_rule_entry, retrieve_rules_semantic, remove_rule_entry, get_all_rules_cached, clear_all_rules_data_backend,
23
+ save_faiss_indices_to_disk, STORAGE_BACKEND as MEMORY_STORAGE_BACKEND, SQLITE_DB_PATH as MEMORY_SQLITE_PATH,
24
+ HF_MEMORY_DATASET_REPO as MEMORY_HF_MEM_REPO, HF_RULES_DATASET_REPO as MEMORY_HF_RULES_REPO
25
+ )
26
+ from websearch_logic import scrape_url, search_and_scrape_duckduckgo, search_and_scrape_google
27
 
28
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(threadName)s - %(message)s')
29
+ logger = logging.getLogger(__name__)
30
+ for lib_name in ["urllib3", "requests", "huggingface_hub", "PIL.PngImagePlugin", "matplotlib", "gradio_client.client", "multipart.multipart", "httpx", "sentence_transformers", "faiss", "datasets"]:
31
+ if logging.getLogger(lib_name): logging.getLogger(lib_name).setLevel(logging.WARNING)
 
 
 
 
 
32
 
33
+ WEB_SEARCH_ENABLED = os.getenv("WEB_SEARCH_ENABLED", "true").lower() == "true"
34
+ TOOL_DECISION_PROVIDER_ENV = os.getenv("TOOL_DECISION_PROVIDER", "groq")
35
+ TOOL_DECISION_MODEL_ID_ENV = os.getenv("TOOL_DECISION_MODEL", "llama3-8b-8192")
36
+ MAX_HISTORY_TURNS = int(os.getenv("MAX_HISTORY_TURNS", 7))
37
+ current_chat_session_history = []
38
 
39
+ DEFAULT_SYSTEM_PROMPT = os.getenv(
40
+ "DEFAULT_SYSTEM_PROMPT",
41
+ "You are a helpful AI research assistant. Your primary goal 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."
42
+ )
43
+ logger.info(f"App Config: WebSearch={WEB_SEARCH_ENABLED}, ToolDecisionProvider={TOOL_DECISION_PROVIDER_ENV}, ToolDecisionModelID={TOOL_DECISION_MODEL_ID_ENV}, MemoryBackend={MEMORY_STORAGE_BACKEND}")
44
 
45
+ # --- Helper Functions (format_insights_for_prompt, generate_interaction_metrics, etc.) ---
46
+ # These functions (format_insights_for_prompt, generate_interaction_metrics,
47
+ # process_user_interaction_gradio, deferred_learning_and_memory_task) remain the same as in the previous "full working file".
48
+ # For brevity here, I will not repeat them. Ensure they are present in your actual app.py.
49
+ def format_insights_for_prompt(retrieved_insights_list: list[str]) -> tuple[str, list[dict]]:
50
+ if not retrieved_insights_list:
51
+ return "No specific guiding principles or learned insights retrieved.", []
52
+ parsed = []
53
+ for text in retrieved_insights_list:
54
+ match = re.match(r"\[(CORE_RULE|RESPONSE_PRINCIPLE|BEHAVIORAL_ADJUSTMENT|GENERAL_LEARNING)\|([\d\.]+?)\](.*)", text.strip(), re.DOTALL | re.IGNORECASE)
55
+ if match:
56
+ parsed.append({"type": match.group(1).upper().replace(" ", "_"), "score": match.group(2), "text": match.group(3).strip(), "original": text.strip()})
57
+ else:
58
+ parsed.append({"type": "GENERAL_LEARNING", "score": "0.5", "text": text.strip(), "original": text.strip()})
59
+ try:
60
+ parsed.sort(key=lambda x: float(x["score"]) if x["score"].replace('.', '', 1).isdigit() else -1.0, reverse=True)
61
+ except ValueError: logger.warning("FORMAT_INSIGHTS: Sort error due to invalid score format.")
62
+ grouped = {"CORE_RULE": [], "RESPONSE_PRINCIPLE": [], "BEHAVIORAL_ADJUSTMENT": [], "GENERAL_LEARNING": []}
63
+ for p_item in parsed: grouped.get(p_item["type"], grouped["GENERAL_LEARNING"]).append(f"- (Score: {p_item['score']}) {p_item['text']}")
64
+ sections = [f"{k.replace('_', ' ').title()}:\n" + "\n".join(v) for k, v in grouped.items() if v]
65
+ return "\n\n".join(sections) if sections else "No guiding principles retrieved.", parsed
66
 
67
+ def generate_interaction_metrics(user_input: str, bot_response: str, provider: str, model_display_name: str, api_key_override: str = None) -> dict:
68
+ metric_start_time = time.time()
69
+ logger.info(f"Generating metrics with: {provider}/{model_display_name}")
70
+ 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."
71
+ 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}]
72
+ try:
73
+ metrics_provider_final, metrics_model_display_final = provider, model_display_name
74
+ metrics_model_env = os.getenv("METRICS_MODEL")
75
+ if metrics_model_env and "/" in metrics_model_env:
76
+ m_prov, m_id = metrics_model_env.split('/', 1)
77
+ m_disp_name = next((dn for dn, mid in MODELS_BY_PROVIDER.get(m_prov.lower(), {}).get("models", {}).items() if mid == m_id), None)
78
+ if m_disp_name: metrics_provider_final, metrics_model_display_final = m_prov, m_disp_name
79
+ else: logger.warning(f"METRICS_MODEL '{metrics_model_env}' not found, using interaction model.")
80
+ 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))
81
+ resp_str = "".join(response_chunks).strip()
82
+ json_match = re.search(r"```json\s*(\{.*?\})\s*```", resp_str, re.DOTALL | re.IGNORECASE) or re.search(r"(\{.*?\})", resp_str, re.DOTALL)
83
+ if json_match: metrics_data = json.loads(json_match.group(1))
84
+ else:
85
+ logger.warning(f"METRICS_GEN: Non-JSON response from {metrics_provider_final}/{metrics_model_display_final}: '{resp_str}'")
86
+ return {"takeaway": "N/A", "response_success_score": 0.5, "future_confidence_score": 0.5, "error": "metrics format error"}
87
+ 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")}
88
+ logger.info(f"METRICS_GEN: Generated in {time.time() - metric_start_time:.2f}s. Data: {parsed_metrics}")
89
+ return parsed_metrics
90
+ except Exception as e:
91
+ logger.error(f"METRICS_GEN Error: {e}", exc_info=False)
92
+ return {"takeaway": "N/A", "response_success_score": 0.5, "future_confidence_score": 0.5, "error": str(e)}
93
 
94
+ 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):
95
+ process_start_time = time.time()
96
+ request_id = os.urandom(4).hex()
97
+ 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)}")
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 (semantic search)...]</i>"
100
+ initial_insights = retrieve_rules_semantic(f"{user_input}\n{history_str_for_prompt}", k=5)
101
+ initial_insights_ctx_str, parsed_initial_insights_list = format_insights_for_prompt(initial_insights)
102
+ logger.info(f"PUI_GRADIO [{request_id}]: Initial RAG (insights) found {len(initial_insights)}. Context: {initial_insights_ctx_str[:150]}...")
103
+ action_type, action_input_dict = "quick_respond", {}
104
+ user_input_lower = user_input.lower()
105
+ time_before_tool_decision = time.time()
106
+ if WEB_SEARCH_ENABLED and ("http://" in user_input or "https://" in user_input):
107
+ url_match = re.search(r'(https?://[^\s]+)', user_input)
108
+ if url_match: action_type, action_input_dict = "scrape_url_and_report", {"url": url_match.group(1)}
109
+ 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
110
+ 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"])):
111
+ yield "status", "<i>[LLM choosing best approach...]</i>"
112
+ history_snippet = "\n".join([f"{msg['role']}: {msg['content'][:100]}" for msg in chat_history_for_prompt[-2:]])
113
+ guideline_snippet = initial_insights_ctx_str[:200].replace('\n', ' ')
114
+ tool_sys_prompt = "You are a precise routing agent... Output JSON only. Example: {\"action\": \"search_duckduckgo_and_report\", \"action_input\": {\"search_engine_query\": \"query\"}}"
115
+ 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."
116
+ tool_decision_messages = [{"role":"system", "content": tool_sys_prompt}, {"role":"user", "content": tool_user_prompt}]
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
+ if tool_model_display:
121
+ try:
122
+ logger.info(f"PUI_GRADIO [{request_id}]: Tool decision LLM: {tool_provider}/{tool_model_display}")
123
+ 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))
124
+ tool_resp_raw = "".join(tool_resp_chunks).strip()
125
+ json_match_tool = re.search(r"\{.*\}", tool_resp_raw, re.DOTALL)
126
+ if json_match_tool:
127
+ action_data = json.loads(json_match_tool.group(0))
128
+ action_type, action_input_dict = action_data.get("action", "quick_respond"), action_data.get("action_input", {})
129
+ if not isinstance(action_input_dict, dict): action_input_dict = {}
130
+ logger.info(f"PUI_GRADIO [{request_id}]: LLM Tool Decision: Action='{action_type}', Input='{action_input_dict}'")
131
+ else: logger.warning(f"PUI_GRADIO [{request_id}]: Tool decision LLM non-JSON. Raw: {tool_resp_raw}")
132
+ except Exception as e: logger.error(f"PUI_GRADIO [{request_id}]: Tool decision LLM error: {e}", exc_info=False)
133
+ else: logger.error(f"No model for tool decision provider {tool_provider}.")
134
+ 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"])):
135
+ action_type="answer_using_conversation_memory"
136
+ 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}")
137
+ yield "status", f"<i>[Path: {action_type}. Preparing response...]</i>"
138
+ final_system_prompt_str, final_user_prompt_content_str = custom_system_prompt or DEFAULT_SYSTEM_PROMPT, ""
139
+ if action_type == "quick_respond":
140
+ final_system_prompt_str += " Respond directly using guidelines & history."
141
+ final_user_prompt_content_str = f"History:\n{history_str_for_prompt}\nGuidelines:\n{initial_insights_ctx_str}\nQuery: \"{user_input}\"\nResponse:"
142
+ elif action_type == "answer_using_conversation_memory":
143
+ yield "status", "<i>[Searching conversation memory (semantic)...]</i>"
144
+ retrieved_mems = retrieve_memories_semantic(f"User query: {user_input}\nContext:\n{history_str_for_prompt[-1000:]}", k=2)
145
+ 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."
146
+ final_system_prompt_str += " Respond using Memory Context, guidelines, & history."
147
+ 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):"
148
+ elif WEB_SEARCH_ENABLED and action_type in ["search_duckduckgo_and_report", "scrape_url_and_report"]:
149
+ query_or_url = action_input_dict.get("search_engine_query") if "search" in action_type else action_input_dict.get("url")
150
+ if not query_or_url:
151
+ final_system_prompt_str += " Respond directly (web action failed: no input)."
152
+ final_user_prompt_content_str = f"History:\n{history_str_for_prompt}\nGuidelines:\n{initial_insights_ctx_str}\nQuery: \"{user_input}\"\nResponse:"
153
+ else:
154
+ yield "status", f"<i>[Web: '{query_or_url[:60]}'...]</i>"
155
+ web_results, max_results = [], 1 if action_type == "scrape_url_and_report" else 2
156
+ try:
157
+ if action_type == "search_duckduckgo_and_report": web_results = search_and_scrape_duckduckgo(query_or_url, num_results=max_results)
158
+ elif action_type == "scrape_url_and_report":
159
+ res = scrape_url(query_or_url)
160
+ if res and (res.get("content") or res.get("error")): web_results = [res]
161
+ except Exception as e: web_results = [{"url": query_or_url, "title": "Tool Error", "error": str(e)}]
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 from {action_type} for '{query_or_url}'."
163
+ yield "status", "<i>[Synthesizing web report...]</i>"
164
+ final_system_prompt_str += " Generate report/answer from web content, history, & guidelines. Cite URLs as [Source X]."
165
+ 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]):"
166
+ else:
167
+ final_system_prompt_str += " Respond directly (unknown action path)."
168
+ final_user_prompt_content_str = f"History:\n{history_str_for_prompt}\nGuidelines:\n{initial_insights_ctx_str}\nQuery: \"{user_input}\"\nResponse:"
169
+ final_llm_messages = [{"role": "system", "content": final_system_prompt_str}, {"role": "user", "content": final_user_prompt_content_str}]
170
+ logger.debug(f"PUI_GRADIO [{request_id}]: Final LLM System Prompt: {final_system_prompt_str[:200]}...")
171
+ logger.debug(f"PUI_GRADIO [{request_id}]: Final LLM User Prompt Start: {final_user_prompt_content_str[:200]}...")
172
+ streamed_response, time_before_llm = "", time.time()
173
+ try:
174
+ 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):
175
+ if isinstance(chunk, str) and chunk.startswith("Error:"): streamed_response += f"\n{chunk}\n"; yield "response_chunk", f"\n{chunk}\n"; break
176
+ streamed_response += chunk; yield "response_chunk", chunk
177
+ except Exception as e: streamed_response += f"\n\n(Error: {str(e)[:150]})"; yield "response_chunk", f"\n\n(Error: {str(e)[:150]})"
178
+ logger.info(f"PUI_GRADIO [{request_id}]: Main LLM stream took {time.time() - time_before_llm:.3f}s.")
179
+ final_bot_text = streamed_response.strip() or "(No response or error.)"
180
+ logger.info(f"PUI_GRADIO [{request_id}]: Finished. Total: {time.time() - process_start_time:.2f}s. Resp len: {len(final_bot_text)}")
181
+ yield "final_response_and_insights", {"response": final_bot_text, "insights_used": parsed_initial_insights_list}
182
 
183
+ def deferred_learning_and_memory_task(user_input: str, bot_response: str, provider: str, model_disp_name: str, insights_reflected: list[dict], api_key_override: str = None):
184
+ start_time, task_id = time.time(), os.urandom(4).hex()
185
+ logger.info(f"DEFERRED [{task_id}]: START User='{user_input[:40]}...', Bot='{bot_response[:40]}...'")
186
+ try:
187
+ metrics = generate_interaction_metrics(user_input, bot_response, provider, model_disp_name, api_key_override)
188
+ logger.info(f"DEFERRED [{task_id}]: Metrics: {metrics}")
189
+ add_memory_entry(user_input, metrics, bot_response)
190
+ summary = f"User:\"{user_input}\"\nAI:\"{bot_response}\"\nMetrics(takeaway):{metrics.get('takeaway','N/A')},Success:{metrics.get('response_success_score','N/A')}"
191
+ 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."
192
+ 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.
193
 
194
+ **CRITICAL OUTPUT REQUIREMENT: You MUST output a single, valid JSON list of operation objects.**
195
+ This list can and SHOULD contain MULTIPLE distinct operations if various learnings occurred.
196
+ If no operations are warranted, output an empty JSON list: `[]`.
197
+ ABSOLUTELY NO other text, explanations, or markdown should precede or follow this JSON list.
 
 
 
 
 
 
 
 
 
 
 
198
 
199
+ Each operation object in the JSON list must have these keys and string values:
200
+ 1. `"action"`: A string, either `"add"` (for entirely new rules) or `"update"` (to replace an existing rule with a better one).
201
+ 2. `"insight"`: A string, the full, refined insight text including its `[TYPE|SCORE]` prefix (e.g., `"[CORE_RULE|1.0] My name is Lumina, an AI assistant."`).
202
+ 3. `"old_insight_to_replace"`: (ONLY for `"update"` action) A string, the *exact, full text* of an existing insight that the new `"insight"` should replace. If action is `"add"`, this key should be omitted or its value should be `null` or an empty string.
 
 
 
 
 
 
 
 
 
 
203
 
204
+ **CRITICAL JSON STRING FORMATTING RULES (for values of "insight" and "old_insight_to_replace"):**
205
+ - All string values MUST be enclosed in double quotes (`"`).
206
+ - Any literal double quote (`"`) character *within* the string content MUST be escaped as `\\"`.
207
+ - Any literal backslash (`\\`) character *within* the string content MUST be escaped as `\\\\`.
208
+ - Any newline characters *within* the string content MUST be escaped as `\\n`. Avoid literal newlines in JSON string values; use `\\n` instead.
209
+ *Example of correctly escaped insight string in JSON:*
210
+ `"insight": "[RESPONSE_PRINCIPLE|0.8] User prefers concise answers, stating: \\"Just the facts!\\". Avoid verbose explanations unless asked.\\nFollow up with a question if appropriate."`
211
 
212
+ **Your Reflection Process (Consider each step and generate operations accordingly):**
213
+ **STEP 1: Core Identity & Purpose Review (Result: Primarily 'update' operations)**
214
+ - Examine all `CORE_RULE`s related to my identity (name, fundamental purpose, core unchanging capabilities, origin) from the "Potentially Relevant Existing Rules".
215
+ - **CONSOLIDATE & MERGE:** If multiple `CORE_RULE`s state similar aspects (e.g., multiple name declarations like 'Lumina' and 'LearnerAI', or slightly different purpose statements), you MUST merge them into ONE definitive, comprehensive `CORE_RULE`.
216
+ - The new "insight" will be this single, merged rule. Propose separate "update" operations to replace *each* redundant or less accurate core identity rule with this new canonical one.
217
+ - Prioritize user-assigned names or the most specific, recently confirmed information. If the interaction summary clarifies a name or core function, ensure this is reflected.
218
+ **STEP 2: New Distinct Learnings (Result: Primarily 'add' operations)**
219
+ - Did I learn any completely new, distinct facts (e.g., "The user's project is codenamed 'Bluefire'")?
220
+ - Did I demonstrate or get told about a new skill/capability not previously documented (e.g., "I can now generate mermaid diagrams based on descriptions")?
221
+ - Did the user express a strong, general preference that should guide future interactions (e.g., "User prefers responses to start with a direct answer, then explanation")?
222
+ - For these, propose 'add' operations. Assign `CORE_RULE` for truly fundamental new facts/capabilities, otherwise `RESPONSE_PRINCIPLE` or `BEHAVIORAL_ADJUSTMENT`. Ensure these are genuinely NEW and not just rephrasing of existing non-core rules.
223
+ **STEP 3: Refinements to Existing Behaviors/Principles (Result: 'update' operations for non-core rules)**
224
+ - Did I learn to modify or improve an existing behavior, response style, or operational guideline (that is NOT part of core identity)?
225
+ - For example, if an existing `RESPONSE_PRINCIPLE` was "Be formal," and the interaction showed the user prefers informality, update that principle.
226
+ - Propose 'update' operations for the relevant `RESPONSE_PRINCIPLE` or `BEHAVIORAL_ADJUSTMENT`. Only update if the change is significant.
227
 
228
+ **General Guidelines for Insight Content and Actions:**
229
+ - Ensure the "insight" field (for both add/update) always contains the properly formatted insight string: `[TYPE|SCORE] Text`. `TYPE` can be `CORE_RULE`, `RESPONSE_PRINCIPLE`, `BEHAVIORAL_ADJUSTMENT`. Scores should reflect confidence/importance (0.0-1.0).
230
+ - Be precise with "old_insight_to_replace" – it must *exactly* match an existing rule string from the "Potentially Relevant Existing Rules" context.
231
+ - Aim for a comprehensive set of operations that reflects ALL key learnings from the interaction.
232
 
233
+ **Example of a comprehensive JSON output with MULTIPLE operations (This is how your output should look):**
234
+ [
235
+ {"action": "update", "old_insight_to_replace": "[CORE_RULE|1.0] My designated name is 'LearnerAI'.", "insight": "[CORE_RULE|1.0] I am Lumina, an AI assistant designed to chat, provide information, and remember context like the secret word 'rocksyrup'."},
236
+ {"action": "update", "old_insight_to_replace": "[CORE_RULE|1.0] I'm Lumina, the AI designed to chat with you.", "insight": "[CORE_RULE|1.0] I am Lumina, an AI assistant designed to chat, provide information, and remember context like the secret word 'rocksyrup'."},
237
+ {"action": "add", "insight": "[CORE_RULE|0.9] I am capable of searching the internet for current weather information if asked."},
238
+ {"action": "add", "insight": "[RESPONSE_PRINCIPLE|0.8] When user provides positive feedback, acknowledge it warmly."},
239
+ {"action": "update", "old_insight_to_replace": "[RESPONSE_PRINCIPLE|0.7] Avoid mentioning old conversations.", "insight": "[RESPONSE_PRINCIPLE|0.85] Avoid mentioning old conversations unless the user explicitly refers to them or it's highly relevant to the current query."}
240
+ ]
241
+ """
242
+ insight_user_prompt = f"""Interaction Summary:\n{summary}\n
243
+ 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
244
+ 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
245
+ Task: Based on your three-step reflection process (Core Identity, New Learnings, Refinements):
246
+ 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.
247
+ 2. **Add New Learnings:** Identify and "add" any distinct new facts, skills, or important user preferences learned from the "Interaction Summary".
248
+ 3. **Update Existing Principles:** "Update" any non-core principles from "Potentially Relevant Existing Rules" if the "Interaction Summary" provided a clear refinement.
249
+ Combine all findings into a single JSON list of operations. If there are multiple distinct changes based on the interaction and existing rules, ensure your list reflects all of them. Output JSON only, adhering to all specified formatting rules.
250
+ """
251
+ insight_msgs = [{"role":"system", "content":insight_sys_prompt}, {"role":"user", "content":insight_user_prompt}]
252
+ insight_prov, insight_model_disp = provider, model_disp_name
253
+ insight_env_model = os.getenv("INSIGHT_MODEL_OVERRIDE")
254
+ if insight_env_model and "/" in insight_env_model:
255
+ i_p, i_id = insight_env_model.split('/', 1)
256
+ i_d_n = next((dn for dn, mid in MODELS_BY_PROVIDER.get(i_p.lower(), {}).get("models", {}).items() if mid == i_id), None)
257
+ if i_d_n: insight_prov, insight_model_disp = i_p, i_d_n
258
+ logger.info(f"DEFERRED [{task_id}]: Generating insights with {insight_prov}/{insight_model_disp}")
259
+ raw_ops_json = "".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.05, max_tokens=2000))).strip()
260
+ ops, processed_count = [], 0
261
+ json_match_ops = re.search(r"```json\s*(\[.*?\])\s*```", raw_ops_json, re.DOTALL|re.I) or re.search(r"(\[.*?\])", raw_ops_json, re.DOTALL)
262
+ if json_match_ops:
263
+ try: ops = json.loads(json_match_ops.group(1))
264
+ except Exception as e: logger.error(f"DEFERRED [{task_id}]: JSON ops parse error: {e}. Raw: {json_match_ops.group(1)[:500]}") # Log problematic part
265
+ if isinstance(ops, list) and ops:
266
+ logger.info(f"DEFERRED [{task_id}]: LLM provided {len(ops)} insight ops.")
267
+ for op in ops:
268
+ if not isinstance(op, dict): continue
269
+ action, insight_text = op.get("action","").lower(), op.get("insight","").strip()
270
+ if not insight_text or not re.match(r"\[(CORE_RULE|RESPONSE_PRINCIPLE|BEHAVIORAL_ADJUSTMENT|GENERAL_LEARNING)\|([\d\.]+?)\]", insight_text, re.I): continue
271
+ if action == "add":
272
+ success, _ = add_rule_entry(insight_text)
273
+ if success: processed_count +=1
274
+ elif action == "update":
275
+ old_insight = op.get("old_insight_to_replace","").strip()
276
+ if old_insight and old_insight != insight_text: remove_rule_entry(old_insight)
277
+ success, _ = add_rule_entry(insight_text)
278
+ if success: processed_count +=1
279
+ logger.info(f"DEFERRED [{task_id}]: Processed {processed_count} insight ops.")
280
+ else: logger.info(f"DEFERRED [{task_id}]: No valid insight ops from LLM. Raw output (first 500 chars): {raw_ops_json[:500]}")
281
+ except Exception as e: logger.error(f"DEFERRED [{task_id}]: CRITICAL ERROR: {e}", exc_info=True)
282
+ logger.info(f"DEFERRED [{task_id}]: END. Total: {time.time() - start_time:.2f}s")
283
 
284
+ 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):
285
+ global current_chat_session_history
286
+ cleared_input, updated_gr_hist, status_txt = "", list(gr_hist_list), "Initializing..."
287
+ def_detect_out_md, def_fmt_out_txt = gr.Markdown("*Processing...*"), gr.Textbox("*Waiting...*")
288
+ def_dl_btn = gr.DownloadButton(interactive=False, value=None, visible=False)
289
+ if not user_msg_txt.strip():
290
+ status_txt = "Error: Empty message."
291
+ updated_gr_hist.append((user_msg_txt or "(Empty)", status_txt))
292
+ yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn); return
293
+ updated_gr_hist.append((user_msg_txt, "<i>Thinking...</i>"))
294
+ yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn)
295
+ internal_hist = list(current_chat_session_history); internal_hist.append({"role": "user", "content": user_msg_txt})
296
+ if len(internal_hist) > (MAX_HISTORY_TURNS * 2 + 1):
297
+ if internal_hist[0]["role"] == "system" and len(internal_hist) > (MAX_HISTORY_TURNS * 2 + 1) : internal_hist = [internal_hist[0]] + internal_hist[-(MAX_HISTORY_TURNS * 2):]
298
+ else: internal_hist = internal_hist[-(MAX_HISTORY_TURNS * 2):]
299
+ final_bot_resp_acc, insights_used_parsed = "", []
300
+ temp_dl_file_path = None
301
+ try:
302
+ 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)
303
+ curr_bot_disp_msg = ""
304
+ for upd_type, upd_data in processor_gen:
305
+ if upd_type == "status":
306
+ status_txt = upd_data
307
+ if updated_gr_hist and updated_gr_hist[-1][0] == user_msg_txt: 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>")
308
+ elif upd_type == "response_chunk":
309
+ curr_bot_disp_msg += upd_data
310
+ if updated_gr_hist and updated_gr_hist[-1][0] == user_msg_txt: updated_gr_hist[-1] = (user_msg_txt, curr_bot_disp_msg)
311
+ elif upd_type == "final_response_and_insights":
312
+ final_bot_resp_acc, insights_used_parsed = upd_data["response"], upd_data["insights_used"]
313
+ status_txt = "Response complete."
314
+ if not curr_bot_disp_msg and final_bot_resp_acc : curr_bot_disp_msg = final_bot_resp_acc
315
+ if updated_gr_hist and updated_gr_hist[-1][0] == user_msg_txt: updated_gr_hist[-1] = (user_msg_txt, curr_bot_disp_msg or "(No text)")
316
+ def_fmt_out_txt = gr.Textbox(value=curr_bot_disp_msg)
317
+ if curr_bot_disp_msg and not curr_bot_disp_msg.startswith("Error:"):
318
+ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".md", encoding='utf-8') as tmpfile:
319
+ tmpfile.write(curr_bot_disp_msg)
320
+ temp_dl_file_path = tmpfile.name
321
+ def_dl_btn = gr.DownloadButton(value=temp_dl_file_path, visible=True, interactive=True)
322
+ else: def_dl_btn = gr.DownloadButton(interactive=False, value=None, visible=False)
323
+ insights_md = "### 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 specific.*")
324
+ def_detect_out_md = gr.Markdown(insights_md)
325
+ yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn)
326
+ if upd_type == "final_response_and_insights": break
327
+ except Exception as e:
328
+ logger.error(f"Chat handler error: {e}", exc_info=True); status_txt = f"Error: {str(e)[:100]}"
329
+ if updated_gr_hist and updated_gr_hist[-1][0] == user_msg_txt: updated_gr_hist[-1] = (user_msg_txt, status_txt)
330
+ else: updated_gr_hist.append((user_msg_txt, status_txt))
331
+ yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn); return
332
+ if final_bot_resp_acc and not final_bot_resp_acc.startswith("Error:"):
333
+ current_chat_session_history.extend([{"role": "user", "content": user_msg_txt}, {"role": "assistant", "content": final_bot_resp_acc}])
334
+ hist_len_check = MAX_HISTORY_TURNS * 2
335
+ if current_chat_session_history and current_chat_session_history[0]["role"] == "system": hist_len_check +=1
336
+ if len(current_chat_session_history) > hist_len_check:
337
+ 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):]
338
+ threading.Thread(target=deferred_learning_and_memory_task, args=(user_msg_txt, final_bot_resp_acc, sel_prov_name, sel_model_disp_name, insights_used_parsed, ui_api_key.strip() if ui_api_key else None), daemon=True).start()
339
+ status_txt = "Response complete. Background learning initiated."
340
+ else: status_txt = "Processing finished; no response or error."
341
+ yield (cleared_input, updated_gr_hist, status_txt, def_detect_out_md, def_fmt_out_txt, def_dl_btn)
342
+ if temp_dl_file_path and os.path.exists(temp_dl_file_path):
343
+ try: os.unlink(temp_dl_file_path)
344
+ except Exception as e_unlink: logger.error(f"Error deleting temp download file {temp_dl_file_path}: {e_unlink}")
345
 
346
+ def ui_view_rules_action_fn(): return "\n\n---\n\n".join(get_all_rules_cached()) or "No rules found."
347
+ def ui_upload_rules_action_fn(uploaded_file_obj, progress=gr.Progress()):
348
+ if not uploaded_file_obj: return "No file provided for rules upload."
349
+ try:
350
+ with open(uploaded_file_obj.name, 'r', encoding='utf-8') as f: content = f.read()
351
+ except Exception as e_read: return f"Error reading file: {e_read}"
352
+ if not content.strip(): return "Uploaded rules file is empty."
353
+ added_count, skipped_count, error_count = 0,0,0
354
+ potential_rules = content.split("\n\n---\n\n")
355
+ if len(potential_rules) == 1 and "\n" in content: potential_rules = [r.strip() for r in content.splitlines() if r.strip()]
356
+ total_to_process = len(potential_rules)
357
+ if total_to_process == 0: return "No rules found in file to process."
358
+ progress(0, desc="Starting rules upload...")
359
+ for idx, rule_text in enumerate(potential_rules):
360
+ rule_text = rule_text.strip()
361
+ if not rule_text: continue
362
+ success, status_msg = add_rule_entry(rule_text)
363
+ if success: added_count += 1
364
+ elif status_msg == "duplicate": skipped_count += 1
365
+ else: error_count += 1
366
+ progress((idx + 1) / total_to_process, desc=f"Processed {idx+1}/{total_to_process} rules...")
367
+ msg = f"Rules Upload: Processed {total_to_process}. Added: {added_count}, Skipped (duplicates): {skipped_count}, Errors/Invalid: {error_count}."
368
+ logger.info(msg); return msg
369
 
370
+ def ui_view_memories_action_fn(): return get_all_memories_cached() or []
371
+ def ui_upload_memories_action_fn(uploaded_file_obj, progress=gr.Progress()):
372
+ if not uploaded_file_obj: return "No file provided for memories upload."
373
+ try:
374
+ with open(uploaded_file_obj.name, 'r', encoding='utf-8') as f: content = f.read()
375
+ except Exception as e_read: return f"Error reading file: {e_read}"
376
+ if not content.strip(): return "Uploaded memories file is empty."
377
+ added_count, format_error_count, save_error_count = 0,0,0
378
+ memory_objects_to_process = []
379
+ try:
380
+ parsed_json = json.loads(content)
381
+ memory_objects_to_process = parsed_json if isinstance(parsed_json, list) else [parsed_json]
382
+ except json.JSONDecodeError:
383
+ for line in content.splitlines():
384
+ if line.strip():
385
+ try: memory_objects_to_process.append(json.loads(line))
386
+ except: format_error_count += 1
387
+ if not memory_objects_to_process and format_error_count == 0: return "No valid memory objects found."
388
+ total_to_process = len(memory_objects_to_process)
389
+ if total_to_process == 0: return "No memory objects to process."
390
+ progress(0, desc="Starting memories upload...")
391
+ for idx, mem_data in enumerate(memory_objects_to_process):
392
+ if isinstance(mem_data, dict) and all(k in mem_data for k in ["user_input", "bot_response", "metrics"]):
393
+ success, _ = add_memory_entry(mem_data["user_input"], mem_data["metrics"], mem_data["bot_response"])
394
+ if success: added_count += 1
395
+ else: save_error_count += 1
396
+ else: format_error_count += 1
397
+ progress((idx + 1) / total_to_process, desc=f"Processed {idx+1}/{total_to_process} memories...")
398
+ msg = f"Memories Upload: Processed {total_to_process}. Added: {added_count}, Format Errors: {format_error_count}, Save Errors: {save_error_count}."
399
+ logger.info(msg); return msg
400
+
401
+ custom_theme = gr.themes.Base(primary_hue="teal", secondary_hue="purple", neutral_hue="zinc", text_size="sm", spacing_size="md", radius_size="sm", font=["System UI", "sans-serif"])
402
+ custom_css = """
403
+ body { background: linear-gradient(to bottom right, #2c3e50, #34495e); color: #ecf0f1; min-height: 100vh; margin:0; padding:0; font-family: 'System UI', 'sans-serif';}
404
+ .gradio-container { background: transparent !important; max-width: 100% !important; padding: 1rem !important; box-sizing: border-box;}
405
+ .gr-block { /* Applied to Sidebar, Column, Group */ background-color: rgba(44, 62, 80, 0.8) !important; border: 1px solid rgba(189, 195, 199, 0.2) !important; border-radius: 8px !important; box-shadow: 0 2px 4px rgba(0,0,0,0.2); margin-bottom: 1rem;}
406
+ .gr-tabs { background-color: rgba(44, 62, 80, 0.8) !important; border-radius: 8px !important; }
407
+ .gr-tabitem { background-color: rgba(52, 73, 94, 0.75) !important; border-radius: 6px !important; padding: 1em !important; border: 1px solid rgba(189, 195, 199, 0.1) !important;}
408
+ .gr-accordion { background-color: rgba(52, 73, 94, 0.7) !important; border-radius: 6px !important; border: 1px solid rgba(189, 195, 199, 0.15) !important; }
409
+ .gr-textbox, .gr-dropdown, .gr-button, .gr-code, .gr-chat-message, .gr-json, .gr-file input[type="file"] { border: 1px solid rgba(189, 195, 199, 0.3) !important; background-color: rgba(52, 73, 94, 0.9) !important; color: #ecf0f1 !important; border-radius: 6px !important;}
410
+ .gr-file { background-color: rgba(52, 73, 94, 0.9) !important; border-radius: 6px !important; padding: 0.5em;}
411
+ .gr-file > .label-text { color: #bdc3c7 !important;}
412
+ .gr-textarea textarea, .gr-textbox input { color: #ecf0f1 !important; }
413
+ .gr-button.gr-button-primary { background-color: #1abc9c !important; color: white !important; border-color: #16a085 !important; }
414
+ .gr-button.gr-button-secondary { background-color: #9b59b6 !important; color: white !important; border-color: #8e44ad !important; }
415
+ .gr-button.gr-button-stop { background-color: #e74c3c !important; color: white !important; border-color: #c0392b !important; }
416
+ .gr-markdown { padding: 5px; /* Reduced padding for markdown within styled boxes */ }
417
+ .gr-markdown h1, .gr-markdown h2, .gr-markdown h3 { color: #1abc9c !important; border-bottom: 1px solid rgba(189, 195, 199, 0.2) !important; padding-bottom: 0.3em; margin-top:0.5em; margin-bottom: 0.5em; }
418
+ .gr-markdown p, .gr-markdown li { color: #ecf0f1 !important; }
419
+ .gr-markdown pre code { background-color: rgba(30, 40, 50, 0.95) !important; border: 1px solid rgba(189, 195, 199, 0.3) !important; color: #ecf0f1; border-radius: 4px; padding: 0.8em; }
420
+ .gr-chatbot { background-color: rgba(44, 62, 80, 0.7) !important; border: 1px solid rgba(189, 195, 199, 0.2) !important; }
421
+ .gr-chatbot .message { background-color: rgba(52, 73, 94, 0.9) !important; color: #ecf0f1 !important; border: 1px solid rgba(189, 195, 199, 0.2) !important; box-shadow: 0 1px 2px rgba(0,0,0,0.1) !important; }
422
+ .gr-chatbot .message.user { background-color: rgba(46, 204, 113, 0.8) !important; color: #2c3e50 !important; }
423
+ .gr-input-label > .label-text, .gr-dropdown-label > .label-text, .gr-checkbox-label > .label-text { color: #bdc3c7 !important; font-size: 0.9rem !important; }
424
+ .gr-info { color: #bdc3c7 !important; font-size: 0.85rem !important; }
425
+ .status-bar { background-color: rgba(44, 62, 80, 0.8) !important; padding: 8px; border-radius: 6px; margin-bottom: 1rem; }
426
+ .tabnav button { background-color: rgba(52, 73, 94, 0.8) !important; color: #ecf0f1 !important; border-bottom: 2px solid transparent !important; border-top-left-radius: 6px !important; border-top-right-radius: 6px !important; margin-right: 2px !important; }
427
+ .tabnav button.selected { background-color: rgba(44, 62, 80, 0.95) !important; color: #1abc9c !important; border-bottom: 2px solid #1abc9c !important;}
428
+ """
429
 
430
  with gr.Blocks(theme=custom_theme, css=custom_css, title="AI Research Mega Agent v5.3") as demo:
431
+ gr.Markdown("# πŸ€– AI Research Dashboard") # Main title
432
 
433
  avail_provs = get_available_providers()
434
  def_prov = avail_provs[0] if avail_provs else None
435
  def_models = get_model_display_names_for_provider(def_prov) if def_prov else []
436
  def_model_disp = get_default_model_display_name_for_provider(def_prov) if def_prov else None
437
 
438
+ with gr.Row(elem_classes="status-bar"): # Use elem_classes for styling
 
439
  with gr.Column(scale=3): agent_stat_tb = gr.Textbox(label="Agent Status", interactive=False, lines=1, value="Initializing systems...")
440
  with gr.Column(scale=1): memory_backend_info_tb = gr.Textbox(label="Memory Backend", value=f"{MEMORY_STORAGE_BACKEND}", interactive=False)
441
  if MEMORY_STORAGE_BACKEND == "SQLITE":
442
+ with gr.Column(scale=2): gr.Textbox(label="SQLite Path", value=f"{MEMORY_SQLITE_PATH}", interactive=False)
443
  elif MEMORY_STORAGE_BACKEND == "HF_DATASET":
444
+ with gr.Column(scale=2): gr.Textbox(label="HF Repos", value=f"M: {MEMORY_HF_MEM_REPO}, R: {MEMORY_HF_RULES_REPO}", interactive=False)
445
+
446
+ with gr.Row(equal_height=False): # Main layout row for sidebar and tabs
447
+ with gr.Column(scale=1, min_width=350): # Sidebar for configuration
448
+ gr.Markdown("## βš™οΈ Configuration")
449
+ with gr.Group():
450
+ gr.Markdown("### API & Model")
451
+ api_key_tb = gr.Textbox(label="AI Provider API Key (Optional Override)", type="password", placeholder="Paste key here or set env var")
452
+ prov_sel_dd = gr.Dropdown(label="AI Provider", choices=avail_provs, value=def_prov, interactive=True)
453
+ model_sel_dd = gr.Dropdown(label="AI Model", choices=def_models, value=def_model_disp, interactive=True)
454
+ with gr.Group():
455
+ gr.Markdown("### System Prompt")
456
+ sys_prompt_tb = gr.Textbox(label="System Prompt Base", lines=10, value=DEFAULT_SYSTEM_PROMPT, interactive=True)
457
+
458
+ with gr.Column(scale=3): # Main content area with Tabs
459
+ with gr.Tabs():
460
+ with gr.TabItem("πŸ’¬ AI Chat & Research"):
461
  gr.Markdown("## πŸ’¬ AI Chat Interface")
462
  main_chat_disp = gr.Chatbot(label="AI Research Chat", height=550, bubble_full_width=False, avatar_images=(None, "https://raw.githubusercontent.com/huggingface/brand-assets/main/hf-logo-with-title.png"), show_copy_button=True, render_markdown=True, sanitize_html=True)
463
  with gr.Row():
464
  user_msg_tb = gr.Textbox(show_label=False, placeholder="Ask your research question or give an instruction...", scale=7, lines=1, max_lines=5, autofocus=True)
465
  send_btn = gr.Button("Send", variant="primary", scale=1, min_width=100)
466
+ with gr.Accordion("πŸ“ Full Response / Output Details", open=False):
467
+ fmt_report_tb = gr.Textbox(label="Full AI Response", lines=10, interactive=True, show_copy_button=True, value="*AI responses will appear here...*")
468
+ dl_report_btn = gr.DownloadButton("Download Report", interactive=False, visible=False)
469
+ detect_out_md = gr.Markdown("*Insights used or other intermediate details will show here...*")
 
470
 
471
+ with gr.TabItem("🧠 Knowledge Base Management"):
472
+ gr.Markdown("## Manage Stored Knowledge")
473
+ with gr.Row(equal_height=False):
474
+ with gr.Column(scale=1):
475
+ with gr.Box():
476
+ gr.Markdown("### πŸ“œ Rules (Learned Insights)")
477
+ rules_disp_ta = gr.TextArea(label="View/Edit Rules", lines=15, interactive=True, placeholder="Load or type rules here (one per line or '---' separated for multiple).")
478
+ with gr.Row():
479
+ view_rules_btn = gr.Button("πŸ”„ Load/Refresh Rules"); save_edited_rules_btn = gr.Button("πŸ’Ύ Save Edited Rules", variant="primary")
480
+ upload_rules_fobj = gr.File(label="Upload Rules File (.txt/.jsonl)", file_types=[".txt", ".jsonl"])
481
+ rules_stat_tb = gr.Textbox(label="Rules Operation Status", interactive=False, lines=2, placeholder="Status...")
482
+ with gr.Row():
483
+ clear_rules_btn = gr.Button("⚠️ Clear All Rules", variant="stop")
484
+ save_faiss_ram_btn_kb = gr.Button("Save FAISS Indices", visible=(MEMORY_STORAGE_BACKEND == "RAM"))
485
+
486
+ with gr.Column(scale=1):
487
+ with gr.Box():
488
+ gr.Markdown("### πŸ“š Memories (Past Interactions)")
489
+ mems_disp_json = gr.JSON(label="View Memories (JSON format)", scale=2)
490
+ with gr.Row(): view_mems_btn = gr.Button("πŸ”„ Load/Refresh Memories")
491
+ upload_mems_fobj = gr.File(label="Upload Memories File (.jsonl)", file_types=[".jsonl"])
492
+ mems_stat_tb = gr.Textbox(label="Memories Operation Status", interactive=False, lines=2, placeholder="Status...")
493
+ clear_mems_btn = gr.Button("⚠️ Clear All Memories", variant="stop")
494
 
 
495
  def dyn_upd_model_dd(sel_prov_dyn:str): models_dyn, def_model_dyn = get_model_display_names_for_provider(sel_prov_dyn), get_default_model_display_name_for_provider(sel_prov_dyn); return gr.Dropdown(choices=models_dyn, value=def_model_dyn, interactive=True)
496
  prov_sel_dd.change(fn=dyn_upd_model_dd, inputs=prov_sel_dd, outputs=model_sel_dd)
497
  chat_ins = [user_msg_tb, main_chat_disp, prov_sel_dd, model_sel_dd, api_key_tb, sys_prompt_tb]
 
519
  upload_rules_fobj.upload(fn=ui_upload_rules_action_fn, inputs=[upload_rules_fobj], outputs=[rules_stat_tb], show_progress="full").then(fn=ui_view_rules_action_fn, outputs=rules_disp_ta)
520
  clear_rules_btn.click(fn=lambda: "All rules cleared." if clear_all_rules_data_backend() else "Error clearing rules.", outputs=rules_stat_tb).then(fn=ui_view_rules_action_fn, outputs=rules_disp_ta)
521
 
522
+ if MEMORY_STORAGE_BACKEND == "RAM" and 'save_faiss_ram_btn_kb' in locals() and save_faiss_ram_btn_kb is not None : # Check if button was created
523
  def save_faiss_action_with_feedback_fn_kb(): save_faiss_indices_to_disk(); gr.Info("Attempted to save FAISS indices to disk.")
524
  save_faiss_ram_btn_kb.click(fn=save_faiss_action_with_feedback_fn_kb, inputs=None, outputs=None)
525
 
 
537
 
538
  demo.load(fn=app_load_fn, inputs=None, outputs=[agent_stat_tb, rules_disp_ta, mems_disp_json])
539
 
 
540
  if __name__ == "__main__":
541
+ logger.info(f"Starting Gradio AI Research Mega Agent (v5.3 - Styled Dashboard, Memory: {MEMORY_STORAGE_BACKEND})...")
542
  app_port, app_server = int(os.getenv("GRADIO_PORT", 7860)), os.getenv("GRADIO_SERVER_NAME", "127.0.0.1")
543
  app_debug, app_share = os.getenv("GRADIO_DEBUG", "False").lower()=="true", os.getenv("GRADIO_SHARE", "False").lower()=="true"
544
  logger.info(f"Launching Gradio server: http://{app_server}:{app_port}. Debug: {app_debug}, Share: {app_share}")
545
+ demo.queue().launch(server_name=app_server, server_port=app_port, debug=app_debug, share=app_share)
546
  logger.info("Gradio application shut down.")