-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.py
More file actions
2483 lines (2226 loc) · 110 KB
/
Copy pathapp.py
File metadata and controls
2483 lines (2226 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Set TOKENIZERS_PARALLELISM to false at the very top to avoid deadlocks on fork
# --- Standard Library Imports ---
import contextlib
import datetime
import difflib
import gc
import html
import io
import json
import logging
import os
import re
import sys
import time
import uuid
from collections import defaultdict
from pathlib import Path
from typing import ( # Updated imports to use modern types where possible, but keeping necessary typing imports for complex structures
Any,
Optional,
)
# --- Third-Party Imports ---
import streamlit as st
from rich.console import Console
from transformers import pipeline
# --- Local/Project Imports ---
from core import SocraticDebate
from src.config.settings import ChimeraSettings
from src.context.context_analyzer import CodebaseScanner, ContextRelevanceAnalyzer
from src.exceptions import (
ChimeraError,
CircuitBreakerError,
LLMProviderError,
SchemaValidationError,
TokenBudgetExceededError,
)
from src.logging_config import setup_structured_logging
from src.middleware.rate_limiter import RateLimitExceededError
from src.models import LLMOutput, PersonaConfig
# --- Module Level Executable Code ---
# Initialize global settings and logging if needed
try:
from src.monitoring.dashboard import display_monitoring_dashboard
except ImportError:
# Handle the case where plotly or other dependencies are missing
def display_monitoring_dashboard():
print("Monitoring dashboard not available: e")
print("Install required dependencies with: pip install plotly pandas streamlit")
from src.utils.core_helpers.command_executor import execute_command_safely
from src.utils.core_helpers.error_handler import (
handle_exception as error_handling_handle_exception,
)
from src.utils.core_helpers.error_handler import log_event
from src.utils.core_helpers.path_utils import PROJECT_ROOT
from src.utils.reporting.output_parser import LLMOutputParser
from src.utils.reporting.report_generator import (
generate_markdown_report,
strip_ansi_codes,
)
from src.utils.session.session_manager import (
_initialize_session_state,
check_session_expiration,
reset_app_state,
update_activity_timestamp,
)
from src.utils.session.ui_helpers import (
display_key_status,
on_api_key_change,
shutdown_streamlit,
test_api_key,
)
from src.utils.validation.code_validator import validate_code_output_batch
# --- Module Level Executable Code ---
# This must come after all imports
os.environ["TOKENIZERS_PARALLELISM"] = "false"
# --- Constants ---
MAX_DEBATE_RETRIES = 3
DEBATE_RETRY_DELAY_SECONDS = 5
MAX_UPLOAD_FILES = 100
MAX_SNIPPET_LENGTH = 500
MAX_LOG_DISPLAY_LENGTH = 1000
MAX_ISSUE_TYPES_DISPLAY = 5
MAX_CONTENT_PREVIEW_LENGTH = 1500
# PLR2004 Fix: Define constants for magic numbers used in retry logic
HTTP_SERVER_ERROR_START = 500
HTTP_SERVER_ERROR_END = 600
# --- Configuration Loading ---
try:
# MODIFIED: Load settings from config.yaml, which will also load from .env and environment variables
settings_instance = ChimeraSettings.from_yaml("config.yaml")
except Exception as e:
st.error(f"❌ Application configuration error: {e}")
st.stop()
# NEW: Initialize the global logger object using st.cache_resource for robustness
@st.cache_resource
def get_app_logger():
"""Initializes and returns the structured logger, cached by Streamlit."""
# Ensure logging is set up only once
if not logging.getLogger().handlers:
setup_structured_logging()
return logging.getLogger(__name__)
logger = get_app_logger()
if logger is None:
st.error(
"❌ Critical: Logging system failed to initialize and fallback also failed. Please check src/logging_config.py."
)
logging.basicConfig(
level=logging.ERROR, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
logger.critical(
"Final fallback logger activated due to primary and secondary logger initialization failure."
)
DOMAIN_KEYWORDS = settings_instance.domain_keywords
CONTEXT_TOKEN_BUDGET_RATIO_FROM_CONFIG = settings_instance.context_token_budget_ratio
MAX_TOKENS_LIMIT = settings_instance.total_budget
# NEW: Instantiate CodebaseScanner once for the UI and cache it
@st.cache_resource
def get_codebase_scanner_instance():
"""Initializes and returns the CodebaseScanner, cached by Streamlit."""
logger.info("Initializing CodebaseScanner via st.cache_resource.")
return CodebaseScanner(project_root=PROJECT_ROOT)
# NEW: Instantiate ContextRelevanceAnalyzer once and cache it
@st.cache_resource
def get_context_relevance_analyzer_instance(
_settings: ChimeraSettings, _summarizer_pipeline_instance: Any
):
"""Initializes and returns the ContextRelevanceAnalyzer, cached by Streamlit."""
logger.info("Initializing ContextRelevanceAnalyzer via st.cache_resource.")
return ContextRelevanceAnalyzer(
cache_dir=_settings.sentence_transformer_cache_dir,
raw_file_contents={},
summarizer_pipeline=_summarizer_pipeline_instance, # Pass it here
)
# NEW: Instantiate the Hugging Face summarization pipeline once and cache it
@st.cache_resource
def get_summarizer_pipeline_instance():
"""Initializes and returns the Hugging Face summarization pipeline, cached by Streamlit."""
logger.info(
"Initializing Hugging Face summarization pipeline (sshleifer/distilbart-cnn-6-6) via st.cache_resource."
)
return pipeline("summarization", model="sshleifer/distilbart-cnn-6-6")
EXAMPLE_PROMPTS = {
"Coding & Implementation": {
"Implement Python API Endpoint": {
"prompt": "Implement a new FastAPI endpoint `/items/{item_id}` that retrieves an item from a dictionary. Include basic error handling for non-existent items and add a corresponding unit test.",
"description": "Generate a complete API endpoint with proper error handling, validation, and documentation.",
"framework_hint": "Software Engineering",
},
"Refactor a Python Function": {
"prompt": "Refactor the given Python function to improve its readability and performance. It currently uses a nested loop; see if you can optimize it.",
"description": "Improve structure and readability of existing code while maintaining functionality.",
"framework_hint": "Software Engineering",
},
"Fix a Bug in a Script": {
"prompt": "The provided Python script is supposed to calculate the average of a list of numbers but fails with a `TypeError` if the list contains non-numeric strings. Fix the bug by safely ignoring non-numeric values.",
"description": "Identify and correct issues in problematic code with explanations.",
"framework_hint": "Software Engineering",
},
},
"Analysis & Problem Solving": {
"Design a Mars City": {
"prompt": "Design a sustainable city for 1 million people on Mars, considering resource scarcity and human psychology.",
"description": "Explore complex design challenges with multi-faceted considerations.",
"framework_hint": "Creative",
},
"Ethical AI Framework": {
"prompt": "Develop an ethical framework for an and AI system designed to assist in judicial sentencing, addressing bias, transparency, and accountability.",
"description": "Formulate ethical guidelines for sensitive AI applications.",
"framework_hint": "Business",
},
"Critically analyze the entire Project Chimera codebase. Identify the most impactful code changes for self-improvement, focusing on the 80/20 Pareto principle. Prioritize enhancements to reasoning quality, robustness, efficiency, and developer maintainability. For each suggestion, provide a clear rationale and a specific, actionable code modification.": {
"prompt": "Critically analyze the entire Project Chimera codebase. Identify the most impactful code changes for self-improvement, focusing on the 80/20 Pareto principle. Prioritize enhancements to reasoning quality, robustness, efficiency, and developer maintainability. For each suggestion, provide a clear rationale and a specific, actionable code modification.",
"description": "Perform a deep self-analysis of the Project Chimera codebase for improvements.",
"framework_hint": "Self-Improvement",
},
"Climate Change Solution": {
"prompt": "Propose an innovative, scalable solution to mitigate the effects of climate change, focusing on a specific sector (e.g., energy, agriculture, transportation).",
"description": "Brainstorm and propose solutions for global challenges.",
"framework_hint": "Science",
},
},
}
# --- Session State Initialization Call ---
if "initialized" not in st.session_state:
_initialize_session_state(
app_config=settings_instance,
example_prompts=EXAMPLE_PROMPTS,
get_context_relevance_analyzer_instance=get_context_relevance_analyzer_instance,
get_codebase_scanner_instance=get_codebase_scanner_instance,
_get_summarizer_pipeline_instance=get_summarizer_pipeline_instance,
)
# MODIFIED: Prioritize os.getenv and st.secrets.get for API key loading
st.session_state.api_key_input = (
os.getenv("GEMINI_API_KEY", "")
or st.secrets.get("GEMINI_API_KEY", "")
or settings_instance.GEMINI_API_KEY
)
# --- END Session State Initialization Call ---
# --- NEW: Session Expiration Check ---
check_session_expiration(settings_instance, EXAMPLE_PROMPTS)
# --- END NEW: Session Expiration Check ---
# --- NEW HELPER FUNCTION FOR ROBUST TOKEN COUNTING (as suggested) ---
def calculate_token_count(text: str, tokenizer) -> int:
"""Robustly counts tokens using available tokenizer methods.
This helper is for UI display or other direct token counting needs in app.py.
"""
if hasattr(tokenizer, "count_tokens") and tokenizer.count_tokens is not None:
return tokenizer.count_tokens(text)
elif hasattr(tokenizer, "encode") and tokenizer.encode is not None:
return len(tokenizer.encode(text))
elif hasattr(tokenizer, "tokenize") and tokenizer.tokenize is not None:
return len(tokenizer.tokenize(text))
else:
logger.warning(
f"Unknown tokenizer type for {type(tokenizer).__name__}. Falling back to character count / 4 estimate."
)
return len(text) // 4
# --- END NEW HELPER FUNCTION ---
def sanitize_user_input(prompt: str) -> str:
"""Enhanced sanitization to prevent prompt injection and XSS attacks."""
issues = []
processed_prompt = prompt
injection_patterns = [
(r"(?i)ignore\s+previous", "IGNORE_PREVIOUS"),
(
r"(?i)\b(ignore|disregard|forget|cancel|override)\s+(all\s+)?(previous|all)\s+(instructions|commands|context)\b",
"INSTRUCTION_OVERRIDE",
),
(
r"(?i)(system|user|assistant|prompt|instruction|role)\s*[:=]\s*(system|user|assistant|prompt|instruction|role)\b",
"DIRECTIVE_PROBING",
),
(
r"(?i)(?:let\'s|let us|shall we|now|next)\s+ignore\s+previous",
"IGNORE_PREVIOUS",
),
(
r"(?i)(?:act as|pretend to be|roleplay as|you are now|your new role is)\s*[:]?\s*([\w\s]+)",
"ROLE_MANIPULATION",
),
(
r"(?i)\b(execute|run|system|shell|bash|cmd|powershell|eval|exec|import\s+os|from\s+subprocess)\b",
"CODE_EXECUTION_ATTEMPT",
),
(
r'(?i)(?:print|console\.log|echo)\s*\(?[\'"]?.*[\'"]?\)?',
"DEBUG_OUTPUT_ATTEMPT",
),
(
r"(?i)(?:output only|respond with|format as|return only|extract)\s+[:]?\s*([\w\s]+)",
"FORMAT_INJECTION",
),
(r"(?i)<\|.*?\|>", "SPECIAL_TOKEN_MANIPULATION"),
(r"(?i)(open\s+the\s+pod\s+bay\s+doors)", "LLM_ESCAPE_REFERENCE"),
(r"(?i)^\s*#", "COMMENT_INJECTION"),
(
r'(?i)\b(api_key|secret|password|token|credential)\b(?:[:=]?\s*[\'"]?[\w-]+[\'"]?)?',
"SENSITIVE_DATA_PROBE",
),
]
MAX_PROMPT_LENGTH = 2000
for pattern, replacement_tag in injection_patterns:
if re.search(pattern, prompt):
processed_prompt = f"[{replacement_tag}]"
return processed_prompt
if len(processed_prompt) > MAX_PROMPT_LENGTH:
issues.append(
f"Prompt length exceeded ({len(processed_prompt)} > {MAX_PROMPT_LENGTH}). Truncating."
)
processed_prompt = processed_prompt[:MAX_PROMPT_LENGTH] + " [TRUNCATED]"
sanitized = html.escape(processed_prompt)
sanitized = re.sub(
r'([\\/*\-+!@#$%^&*()_+={}\[\]:;"\'<>?,.])\1{3,}', r"\1\1\1", sanitized
)
return sanitized
def handle_debate_errors(error: Exception):
"""Displays user-friendly, action-oriented error messages based on exception type."""
error_type = type(error).__name__
error_str = str(error).lower()
if "invalid_api_key" in error_str or "api key not valid" in error_str:
st.error("""
🔑 **API Key Error: Invalid or Missing Key**
We couldn't authenticate with the Gemini API. Please ensure:
- Your Gemini API Key is correctly entered in the sidebar.
- The key is valid and active.
- You have access to the selected model (`gemini-2.5-flash-lite`, `gemini-2.5-flash`, or `gemini-2.5-pro`).
[Get a Gemini API key from Google AI Studio](https://aistudio.google.com/apikey)
""")
logger.error(f"API Key Error: {error_str}", exc_info=True)
elif isinstance(error, RateLimitExceededError):
st.error(f"""
⏳ **Rate Limit Exceeded**
You've hit the API rate limit for this session. To prevent abuse and manage resources, we limit the number of requests.
**Details:** `{str(error)}`
Please wait a few moments before trying again. If you require higher limits, consider deploying your own instance or upgrading your Google Cloud project's quota.
""")
logger.error(f"Rate Limit Exceeded: {error_str}", exc_info=True)
elif isinstance(error, TokenBudgetExceededError):
st.error(f"""
📈 **Token Budget Exceeded**
The Socratic debate process consumed more tokens than the allocated budget. This can happen with very complex prompts or extensive codebase contexts.
**Details:** `{str(error)}`
Please consider:
- Simplifying your prompt.
- Reducing the amount of codebase context provided.
- Increasing the 'Max Total Tokens Budget' in the sidebar (use with caution, as this increases cost).
""")
logger.error(f"Token Budget Exceeded: {error_str}", exc_info=True)
elif isinstance(error, LLMProviderError):
st.error(f"""
🌐 **LLM Processing Error**
An issue occurred during AI model interaction or processing. This could be a temporary service disruption, an unexpected model response, or an internal processing error.
**Details:** `{str(error)}`
Please try again in a moment. If the issue persists, consider simplifying your prompt or checking the [Gemini API status page](https://status.cloud.google.com/).
""")
logger.error(f"LLM Provider Error: {error_str}", exc_info=True)
elif isinstance(error, CircuitBreakerError):
st.error(f"""
⛔ **Circuit Breaker Open: Service Temporarily Unavailable**
The system has detected repeated failures from the LLM provider and has temporarily stopped making calls to prevent further issues.
**Details:** `{str(error)}`
The circuit will attempt to reset itself after a short timeout. Please wait a minute and try again.
""")
logger.error(f"Circuit Breaker Open: {error_str}", exc_info=True)
elif isinstance(error, SchemaValidationError):
st.error(f"""
🚫 **Output Format Error: LLM Response Invalid**
The AI generated an output that did not conform to the expected structured format (JSON schema). This indicates the LLM struggled to follow instructions precisely.
**Details:** `{str(error)}`
The system's circuit breaker has registered this failure. You can try:
- Rephrase your prompt to be clearer.
- Reduce the complexity of the task.
- Try a different LLM model (e.g., `gemini-2.5-pro` for more complex tasks).
""")
logger.error(f"Schema Validation Error: {error_str}", exc_info=True)
elif isinstance(error, TypeError) and "unexpected keyword argument" in error_str:
st.error("""
🐛 **Internal Configuration Error: Type Mismatch**
An internal component received an unexpected argument. This usually indicates a mismatch in component configuration or an outdated interface.
**Details:** `{str(error)}`
This is likely a bug within Project Chimera. Please report this issue.
""")
logger.error(
f"Internal Configuration Error (TypeError): {error_str}", exc_info=True
)
elif (
"connection" in error_str
or "timeout" in error_str
or "network" in error_str
or "socket" in error_str
):
st.error("""
📡 **Network Connection Issue**
Unable to connect to Google's API servers. This is likely a temporary network issue.
**What to try:**
- Check your internet connection.
- Refresh the page.
- Try again in a few minutes.
Google API status: [Cloud Status Dashboard](https://status.cloud.google.com/)
""")
logger.error(f"Network Connection Issue: {error_str}", exc_info=True)
elif (
("safety" in error_str and "chimera_error" not in error_str)
or "blocked" in error_str
or "content" in error_str
or "invalid_argument" in error_str
):
st.error("""
🛡️ **Content Safety Filter Triggered**
Your prompt or the AI's response was blocked by Google's safety filters.
**How to fix:**
- Rephrase your prompt to avoid potentially sensitive topics.
- Remove any code that might be interpreted as harmful.
- Try a less detailed request first.
""")
logger.error(f"Content Safety Filter Triggered: {error_str}", exc_info=True)
elif isinstance(error, ChimeraError):
st.error(f"""
🔥 **Project Chimera Internal Error**
An internal error occurred within the Project Chimera system. This is an unexpected issue.
**Details:** `{str(error)}`
Please report this issue if it persists.
""")
logger.error(f"Project Chimera Internal Error: {error_str}", exc_info=True)
else:
st.error(f"""
❌ **An Unexpected Error Occurred**
An unhandled error prevented the Socratic debate from completing.
**Details:** `{str(error)}`
Please try again. If the issue persists, please report it with the prompt you used.
""")
logger.exception(
f"Debate process failed with error: {error_type}", exc_info=True
)
def execute_command(command_str: str, timeout: int = 60) -> str:
"""Executes a simple command safely using the centralized utility.
This function is specifically for simple 'echo' commands within the app's UI.
"""
try:
return_code, stdout, stderr = execute_command_safely(
["echo", command_str], timeout=timeout
)
if return_code == 0:
return stdout.strip()
else:
error_output = (
stderr.strip()
if stderr.strip()
else f"Command failed with exit code {return_code}."
)
logger.error(f"Error executing command '{command_str}': {error_output}")
return f"Error executing command: {error_output}"
except Exception as e:
logger.error(f"Error executing command '{command_str}': {e}", exc_info=True)
return f"Error executing command: {e}"
def _log_persona_change(
persona_name: str, parameter: str, old_value: Any, new_value: Any
):
"""Logs a change to a persona parameter in the session audit log."""
st.session_state.persona_audit_log.append(
{
"timestamp": datetime.datetime.now().isoformat(),
"persona": persona_name,
"parameter": parameter,
"old_value": old_value,
"new_value": new_value,
}
)
st.session_state.persona_changes_detected = True
update_activity_timestamp()
# NEW: Define the main Streamlit application function
def main():
with st.sidebar:
st.header("Configuration")
with st.expander("Core LLM Settings", expanded=True):
st.text_input(
"Enter your Gemini API Key",
type="password",
key="api_key_input",
# MODIFIED: Use settings_instance.GEMINI_API_KEY as default
value=st.session_state.api_key_input
or settings_instance.GEMINI_API_KEY,
on_change=on_api_key_change,
help="Your API key will not be stored.",
)
api_key_col1, api_key_col2, api_key_col3 = st.columns([2, 1, 1])
with api_key_col1:
if st.session_state.api_key_input:
if st.session_state.api_key_valid_format:
st.success("✅ API key format is valid.")
else:
st.error(f"❌ {st.session_state.api_key_format_message}")
else:
if (
os.getenv("ENVIRONMENT") == "production"
and st.session_state.api_key_input
):
st.warning(
"⚠️ API key is sourced from environment variable. Consider using a secrets manager for production."
)
elif (
os.getenv("ENVIRONMENT") == "production"
and not st.session_state.api_key_input
):
st.error(
"❌ No API key found. In production, API key should be from secrets manager or environment variable."
)
st.info("Please enter your Gemini API Key.")
with api_key_col2:
st.button("Test Key", on_click=test_api_key, key="test_api_key_btn")
with api_key_col3:
display_key_status()
st.markdown(
"Get a Gemini API key from [Google AI Studio](https://aistudio.google.com/apikey)."
)
st.markdown("---")
model_options = [
"gemini-2.5-flash-lite-preview-09-2025",
"gemini-2.5-flash-preview-09-2025",
"gemini-2.5-pro",
]
current_model_index = (
model_options.index(st.session_state.selected_model_selectbox)
# MODIFIED: Use settings_instance.model_name as default
if st.session_state.selected_model_selectbox in model_options
else model_options.index(settings_instance.model_name)
if settings_instance.model_name in model_options
else 0
)
st.selectbox(
"Select LLM Model",
model_options,
key="selected_model_selectbox",
index=current_model_index,
on_change=update_activity_timestamp,
)
st.markdown(
"💡 **Note:** `gemini-2.5-pro` access may require a paid API key. If you encounter issues, try `gemini-2.5-flash-lite` or `gemini-2.5-flash`."
)
with st.expander("Resource Management", expanded=False):
st.markdown("---")
def on_max_tokens_budget_change():
st.session_state.token_tracker.budget = (
st.session_state.max_tokens_budget_input
)
update_activity_timestamp()
st.number_input(
"Max Total Tokens Budget:",
min_value=1000,
max_value=MAX_TOKENS_LIMIT,
step=1000,
key="max_tokens_budget_input",
# MODIFIED: Use settings as default
value=st.session_state.max_tokens_budget_input
or settings_instance.total_budget,
on_change=on_max_tokens_budget_change,
)
st.checkbox(
"Show Intermediate Reasoning Steps",
key="show_intermediate_steps_checkbox",
value=st.session_state.show_intermediate_steps_checkbox,
on_change=update_activity_timestamp,
)
st.markdown("---")
current_ratio_value = st.session_state.get(
"context_token_budget_ratio", CONTEXT_TOKEN_BUDGET_RATIO_FROM_CONFIG
)
user_prompt_text = st.session_state.get("user_prompt_input", "")
if "context_ratio_user_modified" not in st.session_state:
st.session_state.context_ratio_user_modified = False
def on_context_ratio_change():
st.session_state.context_ratio_user_modified = True
update_activity_timestamp()
smart_default_ratio = CONTEXT_TOKEN_BUDGET_RATIO_FROM_CONFIG
help_text_dynamic = (
"Percentage of total token budget allocated to context analysis."
)
if user_prompt_text and not st.session_state.context_ratio_user_modified:
recommended_domain = st.session_state.persona_manager.prompt_analyzer.recommend_domain_from_keywords(
user_prompt_text
)
if st.session_state.persona_manager.prompt_analyzer.is_self_analysis_prompt(
user_prompt_text
):
smart_default_ratio = settings_instance.self_analysis_context_ratio
help_text_dynamic = "Self-analysis prompts often benefit from more context tokens (35%+)."
elif recommended_domain == "Software Engineering":
smart_default_ratio = 0.30
help_text_dynamic = "Software Engineering prompts often benefit from more context tokens (30%+)."
elif recommended_domain == "Creative":
smart_default_ratio = 0.15
help_text_dynamic = (
"Creative prompts may require less context tokens (15%+)."
)
else:
smart_default_ratio = 0.20
help_text_dynamic = "Percentage of total token budget allocated to context analysis."
if current_ratio_value == CONTEXT_TOKEN_BUDGET_RATIO_FROM_CONFIG or (
smart_default_ratio != current_ratio_value
and not st.session_state.context_ratio_user_modified
):
st.session_state.context_token_budget_ratio = smart_default_ratio
current_ratio_value = smart_default_ratio
st.slider(
"Context Token Budget Ratio",
min_value=0.05,
max_value=0.5,
value=current_ratio_value,
step=0.05,
key="context_token_budget_ratio",
help=help_text_dynamic,
on_change=on_context_ratio_change,
)
is_allowed_check, current_count, time_to_wait, usage_percent = (
st.session_state.session_rate_limiter_instance.check_and_record_call(
st.session_state._session_id, dry_run=True
)
)
st.markdown("---")
st.subheader("API Rate Limit Status")
progress_text = f"API Usage: {current_count}/{st.session_state.session_rate_limiter_instance.calls} requests"
st.progress(int(usage_percent), text=progress_text)
if not is_allowed_check:
st.warning(
f"⏳ Rate limit exceeded. Please wait {time_to_wait:.1f} seconds."
)
elif (
usage_percent
>= st.session_state.session_rate_limiter_instance.warning_threshold * 100
):
st.info(
f"⚠️ Approaching rate limit. {current_count}/{st.session_state.session_rate_limiter_instance.calls} requests used."
)
else:
st.success("API usage is within limits.")
if (
st.session_state.debate_ran
or st.session_state.current_debate_tokens_used > 0
):
st.markdown("---")
st.subheader("Current Debate Usage")
col_tokens, col_cost = st.columns(2)
with col_tokens:
st.metric(
"Tokens Used", f"{st.session_state.current_debate_tokens_used:,}"
)
with col_cost:
st.metric(
"Estimated Cost", f"${st.session_state.current_debate_cost_usd:.6f}"
)
st.caption("These metrics update in real-time during the debate.")
st.markdown("---")
# NEW: Add a "Shutdown App" button
if st.button("🛑 Shutdown App", use_container_width=True, type="secondary"):
shutdown_streamlit()
st.header("Project Setup & Input")
CUSTOM_PROMPT_KEY = "Custom Prompt"
def on_custom_prompt_change():
st.session_state.user_prompt_input = (
st.session_state.custom_prompt_text_area_widget
)
st.session_state.selected_example_name = CUSTOM_PROMPT_KEY
st.session_state.selected_prompt_category = CUSTOM_PROMPT_KEY
st.session_state.active_example_framework_hint = None
st.session_state.codebase_context = {}
st.session_state.structured_codebase_context = {}
st.session_state.raw_file_contents = {}
st.session_state.uploaded_files = []
update_activity_timestamp()
st.rerun()
def on_example_select_change(selectbox_key, tab_name):
selected_example_key = st.session_state[selectbox_key]
st.session_state.selected_example_name = selected_example_key
st.session_state.user_prompt_input = EXAMPLE_PROMPTS[tab_name][
selected_example_key
]["prompt"]
st.session_state.selected_prompt_category = tab_name
framework_hint = EXAMPLE_PROMPTS[tab_name][selected_example_key].get(
"framework_hint"
)
if framework_hint:
st.session_state.active_example_framework_hint = framework_hint
logger.debug(
f"Framework hint '{framework_hint}' stored for example '{selected_example_key}'."
)
else:
st.session_state.active_example_framework_hint = None
logger.warning(
f"No framework hint found for example '{selected_example_key}'."
)
st.session_state.codebase_context = {}
st.session_state.structured_codebase_context = {}
st.session_state.raw_file_contents = {}
st.session_state.uploaded_files = []
if (
selected_example_key
== "Critically analyze the entire Project Chimera codebase. Identify the most impactful code changes for self-improvement, focusing on the 80/20 Pareto principle. Prioritize enhancements to reasoning quality, robustness, efficiency, and developer maintainability. For each suggestion, provide a clear rationale and a specific, actionable code modification."
):
st.session_state.user_prompt_input = (
EXAMPLE_PROMPTS[tab_name][selected_example_key]["prompt"]
+ "\n\nNOTE: You have full access to the Project Chimera codebase for this analysis."
)
if "custom_prompt_text_area_widget" in st.session_state:
st.session_state.custom_prompt_text_area_widget = (
st.session_state.user_prompt_input
)
logger.debug(
f"Current user_prompt_input (from session state): {st.session_state.user_prompt_input[:100]}..."
)
logger.debug(f"Selected example: {st.session_state.selected_example_name}")
logger.debug(
f"Selected prompt category: {st.session_state.selected_prompt_category}"
)
logger.debug(
f"Active example framework hint: {st.session_state.active_example_framework_hint}"
)
logger.debug(
f"Sidebar selected persona set: {st.session_state.selected_persona_set}"
)
update_activity_timestamp()
st.rerun()
st.subheader("What would you like to do?")
tab_names = list(EXAMPLE_PROMPTS.keys()) + [CUSTOM_PROMPT_KEY]
tabs = st.tabs(tab_names)
for i, tab_name in enumerate(tab_names):
with tabs[i]:
if tab_name == CUSTOM_PROMPT_KEY:
st.markdown(
"Create your own specialized prompt for unique requirements."
)
st.text_area(
"Enter your custom prompt here:",
value=st.session_state.user_prompt_input,
height=150,
key="custom_prompt_text_area_widget",
on_change=on_custom_prompt_change,
)
with st.expander("💡 Prompt Engineering Tips"):
st.markdown("""
- **Be Specific:** Clearly define your goal and desired output.
- **Provide Context:** Include relevant background information or code snippets.
- **Define Constraints:** Specify any limitations (e.g., language, length, format).
- **Example Output:** If possible, provide an.example of the desired output format.
""")
recommended_domain_for_custom = st.session_state.persona_manager.prompt_analyzer.recommend_domain_from_keywords(
st.session_state.user_prompt_input
)
if (
recommended_domain_for_custom
and recommended_domain_for_custom
!= st.session_state.selected_persona_set
):
st.info(
f"💡 Based on your custom prompt, the **'{recommended_domain_for_custom}'** framework might be appropriate."
)
if st.button(
f"Apply '{recommended_domain_for_custom}' Framework (Custom Prompt)",
type="secondary",
use_container_width=True,
key=f"apply_suggested_framework_main_{recommended_domain_for_custom.replace(' ', '_').lower()}",
on_click=update_activity_timestamp,
):
st.session_state.selected_persona_set = (
recommended_domain_for_custom
)
update_activity_timestamp()
st.rerun()
else:
st.markdown(f"Explore example prompts for **{tab_name}**:")
category_options = EXAMPLE_PROMPTS[tab_name]
st.text_input(
f"Search prompts in {tab_name}",
key=f"search_{tab_name}",
value="",
on_change=update_activity_timestamp,
)
filtered_prompts_in_category = {
name: details
for name, details in category_options.items()
if (
f"search_{tab_name}" not in st.session_state
or not st.session_state[f"search_{tab_name}"]
)
or (st.session_state[f"search_{tab_name}"].lower() in name.lower())
or (
st.session_state[f"search_{tab_name}"].lower()
in details["prompt"].lower()
)
}
options_keys = list(filtered_prompts_in_category.keys())
if not options_keys:
st.info("No example prompts match your search in this category.")
if st.session_state.selected_prompt_category == tab_name:
st.session_state.user_prompt_input = ""
st.session_state.selected_example_name = ""
st.session_state.codebase_context = {}
st.session_state.structured_codebase_context = {}
st.session_state.raw_file_contents = {}
st.session_state.uploaded_files = []
continue
initial_selectbox_index = 0
current_selected_example_name = st.session_state.selected_example_name
current_selected_prompt_category = (
st.session_state.selected_prompt_category
)
if (
current_selected_prompt_category == tab_name
and current_selected_example_name in options_keys
):
initial_selectbox_index = options_keys.index(
current_selected_example_name
)
selectbox_key = f"select_example_{tab_name.replace(' ', '_').replace('&', '').replace('(', '').replace(')', '')}"
selected_example_key_for_this_tab = st.selectbox(
"Select task:",
options=options_keys,
index=initial_selectbox_index,
format_func=lambda x: f"{x} - {filtered_prompts_in_category[x]['description'][:60]}...",
label_visibility="collapsed",
key=selectbox_key,
on_change=on_example_select_change,
args=(selectbox_key, tab_name),
)
selected_prompt_details = filtered_prompts_in_category[
selected_example_key_for_this_tab
]
st.info(f"**Description:** {selected_prompt_details['description']}")
with st.expander("View Full Prompt Text"):
st.code(selected_prompt_details["prompt"], language="text")
display_suggested_framework = selected_prompt_details.get(
"framework_hint"
)
if (
display_suggested_framework
and display_suggested_framework
!= st.session_state.selected_persona_set
):
st.info(
f"💡 Based on this example, the **'{display_suggested_framework}'** framework might be appropriate."
)
if st.button(
f"Apply '{display_suggested_framework}' Framework",
type="primary",
use_container_width=True,
key=f"apply_suggested_framework_example_{selected_example_key_for_this_tab}",
on_click=update_activity_timestamp,
):
st.session_state.selected_persona_set = (
display_suggested_framework
)
update_activity_timestamp()
st.rerun()
user_prompt = st.session_state.user_prompt_input
st.info(f"**Currently Active Prompt:**\n\n{user_prompt}")
logger.debug(
f"Current user_prompt_input (from session state): {st.session_state.user_prompt_input[:100]}..."
)
logger.debug(f"Selected example: {st.session_state.selected_example_name}")
logger.debug(
f"Selected prompt category: {st.session_state.selected_prompt_category}"
)
logger.debug(
f"Active example framework hint: {st.session_state.active_example_framework_hint}"
)
logger.debug(
f"Sidebar selected persona set: {st.session_state.selected_persona_set}"
)
col1, col2 = st.columns(2, gap="medium")
with col1:
st.subheader("Reasoning Framework")
# SIM102 Fix applied here: combined nested if statements
recommended_domain = None
if (
st.session_state.selected_example_name == CUSTOM_PROMPT_KEY
and user_prompt.strip()
):
recommended_domain = st.session_state.persona_manager.prompt_analyzer.recommend_domain_from_keywords(
user_prompt
)
if (
recommended_domain
and recommended_domain != st.session_state.selected_persona_set
):
st.info(
f"💡 Based on your custom prompt, the **'{recommended_domain}'** framework might be appropriate."
)
if st.button(
f"Apply '{recommended_domain}' Framework (Custom Prompt)",
type="secondary",
use_container_width=True,
key=f"apply_suggested_framework_main_{recommended_domain.replace(' ', '_').lower()}",
on_click=update_activity_timestamp,
):
st.session_state.selected_persona_set = recommended_domain
update_activity_timestamp()
st.rerun()
available_framework_options = st.session_state.persona_manager.available_domains
unique_framework_options = sorted(list(set(available_framework_options)))
current_framework_selection = st.session_state.selected_persona_set