Spaces:
Sleeping
Sleeping
Download app.py from Codinainteasy/Looplens: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/spaces/Codinainteasy/Looplens/resolve/main/app.py
- Command line
-
hf download hf://spaces/Codinainteasy/Looplens/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Codinainteasy/Looplens/resolve/main/app.py
12.2 kB
| import gradio as gr | |
| import time | |
| import re | |
| from abc import ABC, abstractmethod | |
| from typing import List, Dict, Any, Generator | |
| # ===================================================================== | |
| # 1. CORE FRAMEWORK & BASE LAYER | |
| # ===================================================================== | |
| class Tool(ABC): | |
| def name(self) -> str: pass | |
| def description(self) -> str: pass | |
| def execute(self, argument: str) -> str: pass | |
| class ShortTermMemory: | |
| def __init__(self, max_items: int = 10): | |
| self.max_items = max_items | |
| self.history: List[Dict[str, str]] = [] | |
| def add(self, role: str, content: str): | |
| self.history.append({"role": role, "content": content}) | |
| if len(self.history) > self.max_items: | |
| self.history.pop(0) | |
| def clear(self): | |
| self.history.clear() | |
| class BaseAgentLoop(ABC): | |
| def __init__(self, tools: List[Tool], memory: ShortTermMemory, max_steps: int = 5): | |
| self.tools = {t.name.lower(): t for t in tools} | |
| self.memory = memory | |
| self.max_steps = max_steps | |
| def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]: | |
| pass | |
| # ===================================================================== | |
| # 2. EXPERT TOOLS LAYER | |
| # ===================================================================== | |
| class WebSearchTool(Tool): | |
| def name(self) -> str: return "Web_Search" | |
| def description(self) -> str: return "Searches the web for quantitative demographics or facts." | |
| def execute(self, argument: str) -> str: | |
| arg = argument.lower() | |
| if "tokyo" in arg: | |
| return "SUCCESS: Tokyo population is approximately 14,000,000." | |
| if "paris" in arg: | |
| return "SUCCESS: Paris population is approximately 2,100,000." | |
| return f"WARNING: Search query '{argument}' yielded no direct demographic records." | |
| class CalculatorTool(Tool): | |
| def name(self) -> str: return "Calculator" | |
| def description(self) -> str: return "Evaluates standard arithmetic expressions natively." | |
| def execute(self, argument: str) -> str: | |
| clean_arg = re.sub(r'[^0-9\+\-\*\/\.\(\)]', '', argument) | |
| if not clean_arg: | |
| return "ERROR: Mathematical input string was empty or contained illegal characters." | |
| try: | |
| result = eval(clean_arg, {"__builtins__": None}, {}) | |
| return f"SUCCESS: Result evaluates to {round(result, 4)}" | |
| except Exception as e: | |
| return f"ERROR: Arithmetic evaluation aborted. Reason: {str(e)}" | |
| # ===================================================================== | |
| # 3. ADVANCED ARCHITECTURAL LOOPS IMPLEMENTATION | |
| # ===================================================================== | |
| class ReActAgent(BaseAgentLoop): | |
| def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]: | |
| self.memory.add("user", query) | |
| yield {"type": "π§ Thought", "content": f"Deconstructing complex query into serial tasks: '{query}'."} | |
| time.sleep(0.4) | |
| yield {"type": "π§ Action", "content": "Invoking Web_Search tool with context: [Tokyo Population Profile]"} | |
| time.sleep(0.3) | |
| tokyo_res = self.tools["web_search"].execute("Tokyo population") | |
| yield {"type": "ποΈ Observation", "content": tokyo_res} | |
| self.memory.add("system", tokyo_res) | |
| time.sleep(0.4) | |
| yield {"type": "π§ Thought", "content": "Target 1 verified (14M). Locating relative baseline: Paris demographics."} | |
| time.sleep(0.4) | |
| yield {"type": "π§ Action", "content": "Invoking Web_Search tool with context: [Paris Population Profile]"} | |
| time.sleep(0.3) | |
| paris_res = self.tools["web_search"].execute("Paris population") | |
| yield {"type": "ποΈ Observation", "content": paris_res} | |
| self.memory.add("system", paris_res) | |
| time.sleep(0.4) | |
| yield {"type": "π§ Thought", "content": "Both components extracted. Compiling division formula: 14000000 / 2100000."} | |
| time.sleep(0.4) | |
| yield {"type": "π§ Action", "content": "Invoking Calculator tool with expression: [14000000 / 2100000]"} | |
| time.sleep(0.3) | |
| calc_res = self.tools["calculator"].execute("14000000 / 2100000") | |
| yield {"type": "ποΈ Observation", "content": calc_res} | |
| time.sleep(0.4) | |
| final_answer = "The relative population ratio of Tokyo to Paris is approximately 6.6667." | |
| yield {"type": "β Final", "content": final_answer} | |
| self.memory.add("assistant", final_answer) | |
| class PlanExecuteAgent(BaseAgentLoop): | |
| def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]: | |
| self.memory.add("user", query) | |
| yield {"type": "π§ Thought", "content": f"Analyzing user intent: '{query}'. Creating immutable macro-execution plan."} | |
| time.sleep(0.5) | |
| plan = ( | |
| "1. Extract Tokyo demographics via Web_Search.\n" | |
| "2. Extract Paris demographics via Web_Search.\n" | |
| "3. Aggregate results and execute floating-point division using Calculator." | |
| ) | |
| yield {"type": "π Plan Generated", "content": plan} | |
| time.sleep(0.6) | |
| yield {"type": "π§ Action", "content": "Executing Step 1: Web_Search -> 'Tokyo population'"} | |
| time.sleep(0.3) | |
| t_res = self.tools["web_search"].execute("Tokyo") | |
| yield {"type": "ποΈ Observation", "content": t_res} | |
| yield {"type": "π§ Action", "content": "Executing Step 2: Web_Search -> 'Paris population'"} | |
| time.sleep(0.3) | |
| p_res = self.tools["web_search"].execute("Paris") | |
| yield {"type": "ποΈ Observation", "content": p_res} | |
| time.sleep(0.4) | |
| yield {"type": "π§ Action", "content": "Executing Step 3: Math Evaluation -> '14000000 / 2100000'"} | |
| time.sleep(0.3) | |
| c_res = self.tools["calculator"].execute("14000000 / 2100000") | |
| yield {"type": "ποΈ Observation", "content": c_res} | |
| time.sleep(0.4) | |
| final_ans = "Plan executed perfectly. Synthesis: Tokyo's population scales 6.67x against Paris." | |
| yield {"type": "β Final", "content": final_ans} | |
| self.memory.add("assistant", final_ans) | |
| class ReflectionAgent(BaseAgentLoop): | |
| def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]: | |
| self.memory.add("user", query) | |
| yield {"type": "π§ Thought", "content": "Attempting single-pass estimation for performance optimization."} | |
| time.sleep(0.4) | |
| yield {"type": "π§ Action", "content": "Estimating quotient based on internal memory weights alone."} | |
| time.sleep(0.3) | |
| initial_guess = "Estimated Ratio: ~7.0 (Based on rough metadata markers)" | |
| yield {"type": "ποΈ Observation", "content": initial_guess} | |
| time.sleep(0.4) | |
| yield {"type": "π Self-Reflection", "content": "CRITICAL ASSESSMENT: Initial heuristic check yields high risk of error margin. Empirical accuracy verification is mandatory. Activating web retrieval tools to correct."} | |
| time.sleep(0.6) | |
| yield {"type": "π§ Action", "content": "Verifying Base Demographics -> Web_Search"} | |
| time.sleep(0.3) | |
| t_pop = self.tools["web_search"].execute("Tokyo") | |
| p_pop = self.tools["web_search"].execute("Paris") | |
| yield {"type": "ποΈ Observation", "content": f"Verified Metrics: Tokyo={t_pop} | Paris={p_pop}"} | |
| time.sleep(0.4) | |
| yield {"type": "π Self-Reflection", "content": "Data retrieved completely. Recalculating precisely to eliminate estimation drift."} | |
| time.sleep(0.4) | |
| yield {"type": "π§ Action", "content": "Executing precise math -> Calculator"} | |
| time.sleep(0.3) | |
| c_res = self.tools["calculator"].execute("14000000/2100000") | |
| yield {"type": "ποΈ Observation", "content": c_res} | |
| time.sleep(0.4) | |
| final_ans = "Refined and validated outcome: Ratio optimized from 7.0 to precisely 6.6667." | |
| yield {"type": "β Final", "content": final_ans} | |
| self.memory.add("assistant", final_ans) | |
| # ===================================================================== | |
| # 4. ORCHESTRATION ENGINE & INTERFACE | |
| # ===================================================================== | |
| def orchestrate_single(architecture: str, query: str) -> Generator[str, None, None]: | |
| memory = ShortTermMemory() | |
| tools = [WebSearchTool(), CalculatorTool()] | |
| if architecture == "ReAct (Reason + Act)": | |
| agent = ReActAgent(tools, memory) | |
| elif architecture == "Plan-Execute": | |
| agent = PlanExecuteAgent(tools, memory) | |
| else: | |
| agent = ReflectionAgent(tools, memory) | |
| log_stream = f"β‘ INITIALIZING AGENT: [{architecture}]\n{'='*50}\n\n" | |
| yield log_stream | |
| for step in agent.run_stream(query): | |
| log_stream += f"[{step['type']}]\nβ‘οΈ {step['content']}\n\n{'-'*40}\n\n" | |
| yield log_stream | |
| def orchestrate_comparison(query: str) -> Generator[List[str], None, None]: | |
| tools = [WebSearchTool(), CalculatorTool()] | |
| react = ReActAgent(tools, ShortTermMemory()) | |
| plan = PlanExecuteAgent(tools, ShortTermMemory()) | |
| reflect = ReflectionAgent(tools, ShortTermMemory()) | |
| react_gen = react.run_stream(query) | |
| plan_gen = plan.run_stream(query) | |
| reflect_gen = reflect.run_stream(query) | |
| react_log, plan_log, reflect_log = "π€ [ReAct Loop]\n\n", "π [Plan-Execute Loop]\n\n", "π [Reflection Loop]\n\n" | |
| react_done = plan_done = reflect_done = False | |
| while not (react_done and plan_done and reflect_done): | |
| if not react_done: | |
| try: | |
| step = next(react_gen) | |
| react_log += f"[{step['type']}]\nβ’ {step['content']}\n\n" | |
| except StopIteration: | |
| react_done = True | |
| if not plan_done: | |
| try: | |
| step = next(plan_gen) | |
| plan_log += f"[{step['type']}]\nβ’ {step['content']}\n\n" | |
| except StopIteration: | |
| plan_done = True | |
| if not reflect_done: | |
| try: | |
| step = next(reflect_gen) | |
| reflect_log += f"[{step['type']}]\nβ’ {step['content']}\n\n" | |
| except StopIteration: | |
| reflect_done = True | |
| yield [react_log, plan_log, reflect_log] | |
| # ===================================================================== | |
| # 5. GRADIO UI | |
| # ===================================================================== | |
| with gr.Blocks(title="LoopLens - Agent Architecture Visualizer") as demo: | |
| gr.Markdown("# π LoopLens") | |
| gr.Markdown("Visualize how different agent architectures (ReAct, Plan-Execute, Reflection) process the same query.") | |
| with gr.Tab("Single Architecture"): | |
| arch_dd = gr.Dropdown( | |
| choices=["ReAct (Reason + Act)", "Plan-Execute", "Reflection"], | |
| value="ReAct (Reason + Act)", | |
| label="Select Architecture" | |
| ) | |
| query_in = gr.Textbox( | |
| label="Query", | |
| value="How many times larger is Tokyo's population than Paris's?", | |
| lines=2 | |
| ) | |
| out_single = gr.Textbox(label="Execution Log", lines=25) | |
| btn_single = gr.Button("βΆοΈ Run Single Agent", variant="primary") | |
| btn_single.click( | |
| fn=orchestrate_single, | |
| inputs=[arch_dd, query_in], | |
| outputs=out_single | |
| ) | |
| with gr.Tab("Compare All Architectures"): | |
| query_cmp = gr.Textbox( | |
| label="Query", | |
| value="How many times larger is Tokyo's population than Paris's?", | |
| lines=2 | |
| ) | |
| out_react = gr.Textbox(label="ReAct Log", lines=15) | |
| out_plan = gr.Textbox(label="Plan-Execute Log", lines=15) | |
| out_reflect = gr.Textbox(label="Reflection Log", lines=15) | |
| btn_cmp = gr.Button("βΆοΈ Run Comparison", variant="primary") | |
| btn_cmp.click( | |
| fn=orchestrate_comparison, | |
| inputs=query_cmp, | |
| outputs=[out_react, out_plan, out_reflect] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() | |