Codinainteasy commited on
Commit
df5c8e7
Β·
verified Β·
1 Parent(s): 81228f4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +213 -0
app.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import time
3
+ import re
4
+ from abc import ABC, abstractmethod
5
+ from typing import List, Dict, Any, Generator
6
+
7
+ # =====================================================================
8
+ # 1. CORE CORE FRAMEWORK & BASE LAYER
9
+ # =====================================================================
10
+
11
+ class Tool(ABC):
12
+ @property
13
+ @abstractmethod
14
+ def name(self) -> str: pass
15
+
16
+ @property
17
+ @abstractmethod
18
+ def description(self) -> str: pass
19
+
20
+ @abstractmethod
21
+ def execute(self, argument: str) -> str: pass
22
+
23
+ class ShortTermMemory:
24
+ def __init__(self, max_items: int = 10):
25
+ self.max_items = max_items
26
+ self.history: List[Dict[str, str]] = []
27
+
28
+ def add(self, role: str, content: str):
29
+ self.history.append({"role": role, "content": content})
30
+ if len(self.history) > self.max_items:
31
+ self.history.pop(0)
32
+
33
+ def clear(self):
34
+ self.history.clear()
35
+
36
+ class BaseAgentLoop(ABC):
37
+ def __init__(self, tools: List[Tool], memory: ShortTermMemory, max_steps: int = 5):
38
+ self.tools = {t.name.lower(): t for t in tools}
39
+ self.memory = memory
40
+ self.max_steps = max_steps
41
+
42
+ @abstractmethod
43
+ def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]:
44
+ pass
45
+
46
+ # =====================================================================
47
+ # 2. EXPERT TOOLS LAYER
48
+ # =====================================================================
49
+
50
+ class WebSearchTool(Tool):
51
+ @property
52
+ def name(self) -> str: return "Web_Search"
53
+
54
+ @property
55
+ def description(self) -> str: return "Searches the web for quantitative demographics or facts."
56
+
57
+ def execute(self, argument: str) -> str:
58
+ arg = argument.lower()
59
+ if "tokyo" in arg:
60
+ return "SUCCESS: Tokyo population is approximately 14,000,000."
61
+ if "paris" in arg:
62
+ return "SUCCESS: Paris population is approximately 2,100,000."
63
+ return f"WARNING: Search query '{argument}' yielded no direct demographic records."
64
+
65
+ class CalculatorTool(Tool):
66
+ @property
67
+ def name(self) -> str: return "Calculator"
68
+
69
+ @property
70
+ def description(self) -> str: return "Evaluates standard arithmetic expressions natively."
71
+
72
+ def execute(self, argument: str) -> str:
73
+ clean_arg = re.sub(r'[^0-9\+\-\*\/\.\(\)]', '', argument)
74
+ if not clean_arg:
75
+ return "ERROR: Mathematical input string was empty or contained illegal characters."
76
+ try:
77
+ result = eval(clean_arg, {"__builtins__": None}, {})
78
+ return f"SUCCESS: Result evaluates to {round(result, 4)}"
79
+ except Exception as e:
80
+ return f"ERROR: Arithmetic evaluation aborted. Reason: {str(e)}"
81
+
82
+ # =====================================================================
83
+ # 3. ADVANCED ARCHITECTURAL LOOPS IMPLEMENTATION
84
+ # =====================================================================
85
+
86
+ class ReActAgent(BaseAgentLoop):
87
+ def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]:
88
+ self.memory.add("user", query)
89
+ yield {"type": "🧠 Thought", "content": f"Deconstructing complex query into serial tasks: '{query}'."}
90
+ time.sleep(0.4)
91
+ yield {"type": "πŸ”§ Action", "content": "Invoking Web_Search tool with context: [Tokyo Population Profile]"}
92
+ time.sleep(0.3)
93
+ tokyo_res = self.tools["web_search"].execute("Tokyo population")
94
+ yield {"type": "πŸ‘οΈ Observation", "content": tokyo_res}
95
+ self.memory.add("system", tokyo_res)
96
+ time.sleep(0.4)
97
+ yield {"type": "🧠 Thought", "content": "Target 1 verified (14M). Locating relative baseline: Paris demographics."}
98
+ time.sleep(0.4)
99
+ yield {"type": "πŸ”§ Action", "content": "Invoking Web_Search tool with context: [Paris Population Profile]"}
100
+ time.sleep(0.3)
101
+ paris_res = self.tools["web_search"].execute("Paris population")
102
+ yield {"type": "πŸ‘οΈ Observation", "content": paris_res}
103
+ self.memory.add("system", paris_res)
104
+ time.sleep(0.4)
105
+ yield {"type": "🧠 Thought", "content": "Both components extracted. Compiling division formula: 14000000 / 2100000."}
106
+ time.sleep(0.4)
107
+ yield {"type": "πŸ”§ Action", "content": "Invoking Calculator tool with expression: [14000000 / 2100000]"}
108
+ time.sleep(0.3)
109
+ calc_res = self.tools["calculator"].execute("14000000 / 2100000")
110
+ yield {"type": "πŸ‘οΈ Observation", "content": calc_res}
111
+ time.sleep(0.4)
112
+ final_answer = "The relative population ratio of Tokyo to Paris is approximately 6.6667."
113
+ yield {"type": "βœ… Final", "content": final_answer}
114
+ self.memory.add("assistant", final_answer)
115
+
116
+ class PlanExecuteAgent(BaseAgentLoop):
117
+ def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]:
118
+ self.memory.add("user", query)
119
+ yield {"type": "🧠 Thought", "content": f"Analyzing user intent: '{query}'. Creating immutable macro-execution plan."}
120
+ time.sleep(0.5)
121
+ plan = (
122
+ "1. Extract Tokyo demographics via Web_Search.\n"
123
+ "2. Extract Paris demographics via Web_Search.\n"
124
+ "3. Aggregate results and execute floating-point division using Calculator."
125
+ )
126
+ yield {"type": "πŸ“‹ Plan Generated", "content": plan}
127
+ time.sleep(0.6)
128
+ yield {"type": "πŸ”§ Action", "content": "Executing Step 1: Web_Search -> 'Tokyo population'"}
129
+ time.sleep(0.3)
130
+ t_res = self.tools["web_search"].execute("Tokyo")
131
+ yield {"type": "πŸ‘οΈ Observation", "content": t_res}
132
+ yield {"type": "πŸ”§ Action", "content": "Executing Step 2: Web_Search -> 'Paris population'"}
133
+ time.sleep(0.3)
134
+ p_res = self.tools["web_search"].execute("Paris")
135
+ yield {"type": "πŸ‘οΈ Observation", "content": p_res}
136
+ time.sleep(0.4)
137
+ yield {"type": "πŸ”§ Action", "content": "Executing Step 3: Math Evaluation -> '14000000 / 2100000'"}
138
+ time.sleep(0.3)
139
+ c_res = self.tools["calculator"].execute("14000000 / 2100000")
140
+ yield {"type": "πŸ‘οΈ Observation", "content": c_res}
141
+ time.sleep(0.4)
142
+ final_ans = "Plan executed perfectly. Synthesis: Tokyo's population scales 6.67x against Paris."
143
+ yield {"type": "βœ… Final", "content": final_ans}
144
+ self.memory.add("assistant", final_ans)
145
+
146
+ class ReflectionAgent(BaseAgentLoop):
147
+ def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]:
148
+ self.memory.add("user", query)
149
+ yield {"type": "🧠 Thought", "content": "Attempting single-pass estimation for performance optimization."}
150
+ time.sleep(0.4)
151
+ yield {"type": "πŸ”§ Action", "content": "Estimating quotient based on internal memory weights alone."}
152
+ time.sleep(0.3)
153
+ initial_guess = "Estimated Ratio: ~7.0 (Based on rough metadata markers)"
154
+ yield {"type": "πŸ‘οΈ Observation", "content": initial_guess}
155
+ time.sleep(0.4)
156
+ 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."}
157
+ time.sleep(0.6)
158
+ yield {"type": "πŸ”§ Action", "content": "Verifying Base Demographics -> Web_Search"}
159
+ time.sleep(0.3)
160
+ t_pop = self.tools["web_search"].execute("Tokyo")
161
+ p_pop = self.tools["web_search"].execute("Paris")
162
+ yield {"type": "πŸ‘οΈ Observation", "content": f"Verified Metrics: Tokyo={t_pop} | Paris={p_pop}"}
163
+ time.sleep(0.4)
164
+ yield {"type": "πŸ” Self-Reflection", "content": "Data retrieved completely. Recalculating precisely to eliminate estimation drift."}
165
+ time.sleep(0.4)
166
+ yield {"type": "πŸ”§ Action", "content": "Executing precise math -> Calculator"}
167
+ time.sleep(0.3)
168
+ c_res = self.tools["calculator"].execute("14000000/2100000")
169
+ yield {"type": "πŸ‘οΈ Observation", "content": c_res}
170
+ time.sleep(0.4)
171
+ final_ans = "Refined and validated outcome: Ratio optimized from 7.0 to precisely 6.6667."
172
+ yield {"type": "βœ… Final", "content": final_ans}
173
+ self.memory.add("assistant", final_ans)
174
+
175
+ # =====================================================================
176
+ # 4. ORCHESTRATION ENGINE & INTERFACE
177
+ # =====================================================================
178
+
179
+ def orchestrate_single(architecture: str, query: str) -> Generator[str, None, None]:
180
+ memory = ShortTermMemory()
181
+ tools = [WebSearchTool(), CalculatorTool()]
182
+ if architecture == "ReAct (Reason + Act)":
183
+ agent = ReActAgent(tools, memory)
184
+ elif architecture == "Plan-Execute":
185
+ agent = PlanExecuteAgent(tools, memory)
186
+ else:
187
+ agent = ReflectionAgent(tools, memory)
188
+ log_stream = f"⚑ INITIALIZING AGENT: [{architecture}]\n{'='*50}\n\n"
189
+ yield log_stream
190
+ for step in agent.run_stream(query):
191
+ log_stream += f"[{step['type']}]\n➑️ {step['content']}\n\n{'-'*40}\n\n"
192
+ yield log_stream
193
+
194
+ def orchestrate_comparison(query: str) -> Generator[List[str], None, None]:
195
+ tools = [WebSearchTool(), CalculatorTool()]
196
+ react = ReActAgent(tools, ShortTermMemory())
197
+ plan = PlanExecuteAgent(tools, ShortTermMemory())
198
+ reflect = ReflectionAgent(tools, ShortTermMemory())
199
+ react_gen = react.run_stream(query)
200
+ plan_gen = plan.run_stream(query)
201
+ reflect_gen = reflect.run_stream(query)
202
+ react_log, plan_log, reflect_log = "πŸ€– [ReAct Loop]\n\n", "πŸ“‹ [Plan-Execute Loop]\n\n", "πŸ” [Reflection Loop]\n\n"
203
+ react_done = plan_done = reflect_done = False
204
+ while not (react_done and plan_done and reflect_done):
205
+ if not react_done:
206
+ try:
207
+ step = next(react_gen)
208
+ react_log += f"[{step['type']}]\nβ€’ {step['content']}\n\n"
209
+ except StopIteration:
210
+ react_done = True
211
+ if not plan_done:
212
+ try:
213
+ step = next(plan_gen)