File size: 12,217 Bytes
df5c8e7
 
 
 
 
 
 
2b06da2
df5c8e7
 
 
 
 
 
2b06da2
df5c8e7
 
 
2b06da2
df5c8e7
 
 
 
 
 
 
2b06da2
df5c8e7
 
 
 
2b06da2
df5c8e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b06da2
df5c8e7
 
2b06da2
df5c8e7
 
 
 
 
 
 
 
 
 
 
2b06da2
df5c8e7
 
2b06da2
df5c8e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b06da2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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):
    @property
    @abstractmethod
    def name(self) -> str: pass

    @property
    @abstractmethod
    def description(self) -> str: pass

    @abstractmethod
    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

    @abstractmethod
    def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]:
        pass

# =====================================================================
# 2. EXPERT TOOLS LAYER
# =====================================================================

class WebSearchTool(Tool):
    @property
    def name(self) -> str: return "Web_Search"

    @property
    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):
    @property
    def name(self) -> str: return "Calculator"

    @property
    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()