Spaces:
Sleeping
Sleeping
| # ./dream_agent.py | |
| """ | |
| By design, the dream_agent will only inspect, analyze, and report. It operates like an engineering consultant presenting a formal change proposal. It will generate a clear visual report of what it wants to optimize, but it is programmatically barred from altering a single character of the source code until the end-user explicitly clicks 'Apply Changes'. If clicked 'Discard', the proposal is immediately deleted from memory, leaving files completely untouched. | |
| To achieve this cleanly, dream_agent.py is built to extract code modifications using structured XML tags (<proposed_patch>...</proposed_patch>). The app will display the text outside these tags as the review proposal, while storing the raw code safely inside a hidden Gradio State component until chosen to authorize or kill the transaction. | |
| The standalone module - dream_agent.py - reads the workspace targets, consults dream.md protocols, executes a non-destructive simulation via llama-3.1-8b-instant, and formats the actionable proposal layout. | |
| """ | |
| import os | |
| import re | |
| from groq import Groq # Substituted automatically if utilizing alternative client wrappers | |
| def execute_dream_reflection(target_file="core_logic.py"): | |
| """ | |
| Phase 1: Deep Cognitive Audit Run | |
| Reads local workspace files and drafts optimized changes without writing them to disk. | |
| """ | |
| # 1. Verification Guardrails | |
| if not os.path.exists(target_file): | |
| return f"### β Audit Aborted\nTarget workspace asset `{target_file}` could not be located for tracing." | |
| if not os.path.exists("dream.md"): | |
| return "### β Audit Aborted\nCognitive ruleset configuration `dream.md` is missing from root." | |
| # 2. Ingest Environment Source Files | |
| with open(target_file, "r", encoding="utf-8") as f: | |
| source_code = f.read() | |
| with open("dream.md", "r", encoding="utf-8") as f: | |
| dream_rules = f.read() | |
| # 3. Initialize Independent Client API | |
| # Uses the same environment token configuration pattern as core_logic/storage | |
| #client = Groq(api_key=os.getenv("GROQ_API_KEY") or os.getenv("HF_TOKEN")) | |
| client = Groq(api_key=os.getenv("GROQ_API_KEY") or os.getenv("HF_TOKEN")) | |
| # 4. Construct Isolated Simulation Prompt | |
| simulation_prompt = f"""{dream_rules} | |
| You are running a deep structural code simulation. Analyze the following live Python file for efficiency bottlenecks, redundant structures, or logic holes. | |
| LIVE WORKSPACE CODE TARGET: `{target_file}` | |
| ```python | |
| {source_code} | |
| CRITICAL COMPILATION MATRIX FOR YOUR OUTPUT: | |
| Provide a clear Markdown analysis of what you found under "ποΈ ANALYSIS SUMMARY". | |
| Provide the complete, production-ready replacement code under "π TARGET PATCH PROPOSAL". | |
| Wrap your replacement code EXACTLY within structural <proposed_patch> and </proposed_patch> tags. | |
| YOUR RESPONSE MUST FOLLOW THIS EXACT TEMPLATE: | |
| ποΈ ANALYSIS SUMMARY | |
| [Detail the exact code gaps, risks, or performance debt you identified here] | |
| π TARGET PATCH PROPOSAL | |
| <proposed_patch> | |
| Complete, modified ready-to-run replacement code block goes here | |
| </proposed_patch> | |
| """ | |
| """ | |
| Note on max_tokens -> When making an API call to Groq without a max_tokens parameter, the server does not leave the window wide open. Instead, it applies a provider-side default cap. For most execution endpoints running Llama 3.1 models, if no parameter is specified, the engine typically cuts off or caps the generation token pool automatically (often default-limited at around 1024 or 2048 tokens). | |
| """ | |
| try: | |
| completion = client.chat.completions.create( | |
| model="llama-3.1-8b-instant", | |
| messages=[{"role": "user", "content": simulation_prompt}], | |
| temperature=0.0, # Force absolute deterministic logic pathing | |
| max_tokens=4096, # Allots enough context space to prevent truncation loops | |
| top_p=1.0 # Works alongside temp=0.0 to focus token selection tightly | |
| ) | |
| proposal_payload = completion.choices[0].message.content | |
| return proposal_payload | |
| except Exception as simulation_error: | |
| return f"### β Cognitive Run Exception\nAPI interaction layer encountered an execution fault: {str(simulation_error)}" | |
| def apply_authorized_patch(proposal_text, target_file="core_logic.py"): | |
| """ | |
| Phase 2: Gated Confirmation Commit Execution | |
| Extracts code from XML tags, creates a rollback backup, and overwrites the target file. | |
| """ | |
| try: | |
| # Extract content between <proposed_patch> tags | |
| patch_match = re.search(r"<proposed_patch>([\s\S]*?)</proposed_patch>", proposal_text) | |
| if not patch_match: | |
| return "β **Patch Aborted:** Could not extract structural `<proposed_patch>` bounds from model proposal." | |
| clean_extracted_code = patch_match.group(1).strip() | |
| # Strip away markdown code block wrappers if the model wrapped them inside the XML tags | |
| if clean_extracted_code.startswith("```python"): | |
| clean_extracted_code = clean_extracted_code[9:] | |
| if clean_extracted_code.startswith("```"): | |
| clean_extracted_code = clean_extracted_code[3:] | |
| if clean_extracted_code.endswith("```"): | |
| clean_extracted_code = clean_extracted_code[:-3] | |
| clean_extracted_code = clean_extracted_code.strip() | |
| # Safety Step: Establish a recovery point backup before committing changes | |
| if os.path.exists(target_file): | |
| backup_path = f"{target_file}.bak" | |
| import shutil | |
| shutil.copy2(target_file, backup_path) | |
| print(f"[+] Local rollback checkpoint generated at: {backup_path}") | |
| # Execute File Writing Commit Transaction | |
| with open(target_file, "w", encoding="utf-8") as f: | |
| f.write(clean_extracted_code) | |
| return f"β **Environment Patched Successfully:** `{target_file}` has been updated. Rollback backup preserved at `{target_file}.bak`." | |
| except Exception as write_fault: | |
| return f"β **Systemic Write Failure:** Execution aborted while updating file system: {str(write_fault)}" | |