Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,230 +0,0 @@
|
|
| 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 |
-
"""Yields execution logs step by step."""
|
| 45 |
-
pass
|
| 46 |
-
|
| 47 |
-
# =====================================================================
|
| 48 |
-
# 2. EXPERT TOOLS LAYER (Fact Processing Engines)
|
| 49 |
-
# =====================================================================
|
| 50 |
-
|
| 51 |
-
class WebSearchTool(Tool):
|
| 52 |
-
@property
|
| 53 |
-
def name(self) -> str: return "Web_Search"
|
| 54 |
-
|
| 55 |
-
@property
|
| 56 |
-
def description(self) -> str: return "Searches the web for quantitative demographics or facts."
|
| 57 |
-
|
| 58 |
-
def execute(self, argument: str) -> str:
|
| 59 |
-
arg = argument.lower()
|
| 60 |
-
if "tokyo" in arg:
|
| 61 |
-
return "SUCCESS: Tokyo population is approximately 14,000,000."
|
| 62 |
-
if "paris" in arg:
|
| 63 |
-
return "SUCCESS: Paris population is approximately 2,100,000."
|
| 64 |
-
return f"WARNING: Search query '{argument}' yielded no direct demographic records."
|
| 65 |
-
|
| 66 |
-
class CalculatorTool(Tool):
|
| 67 |
-
@property
|
| 68 |
-
def name(self) -> str: return "Calculator"
|
| 69 |
-
|
| 70 |
-
@property
|
| 71 |
-
def description(self) -> str: return "Evaluates standard arithmetic expressions natively."
|
| 72 |
-
|
| 73 |
-
def execute(self, argument: str) -> str:
|
| 74 |
-
clean_arg = re.sub(r'[^0-9\+\-\*\/\.\(\)]', '', argument)
|
| 75 |
-
if not clean_arg:
|
| 76 |
-
return "ERROR: Mathematical input string was empty or contained illegal characters."
|
| 77 |
-
try:
|
| 78 |
-
result = eval(clean_arg, {"__builtins__": None}, {})
|
| 79 |
-
return f"SUCCESS: Result evaluates to {round(result, 4)}"
|
| 80 |
-
except Exception as e:
|
| 81 |
-
return f"ERROR: Arithmetic evaluation aborted. Reason: {str(e)}"
|
| 82 |
-
|
| 83 |
-
# =====================================================================
|
| 84 |
-
# 3. ADVANCED ARCHITECTURAL LOOPS IMPLEMENTATION
|
| 85 |
-
# =====================================================================
|
| 86 |
-
|
| 87 |
-
class ReActAgent(BaseAgentLoop):
|
| 88 |
-
"""Interleaved Reasoning and Acting (Thought -> Action -> Observation)"""
|
| 89 |
-
def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]:
|
| 90 |
-
self.memory.add("user", query)
|
| 91 |
-
|
| 92 |
-
yield {"type": "🧠 Thought", "content": f"Deconstructing complex query into serial tasks: '{query}'."}
|
| 93 |
-
time.sleep(0.4)
|
| 94 |
-
|
| 95 |
-
yield {"type": "🔧 Action", "content": "Invoking Web_Search tool with context: [Tokyo Population Profile]"}
|
| 96 |
-
time.sleep(0.3)
|
| 97 |
-
tokyo_res = self.tools["web_search"].execute("Tokyo population")
|
| 98 |
-
yield {"type": "👁️ Observation", "content": tokyo_res}
|
| 99 |
-
self.memory.add("system", tokyo_res)
|
| 100 |
-
time.sleep(0.4)
|
| 101 |
-
|
| 102 |
-
yield {"type": "🧠 Thought", "content": "Target 1 verified (14M). Locating relative baseline: Paris demographics."}
|
| 103 |
-
time.sleep(0.4)
|
| 104 |
-
|
| 105 |
-
yield {"type": "🔧 Action", "content": "Invoking Web_Search tool with context: [Paris Population Profile]"}
|
| 106 |
-
time.sleep(0.3)
|
| 107 |
-
paris_res = self.tools["web_search"].execute("Paris population")
|
| 108 |
-
yield {"type": "👁️ Observation", "content": paris_res}
|
| 109 |
-
self.memory.add("system", paris_res)
|
| 110 |
-
time.sleep(0.4)
|
| 111 |
-
|
| 112 |
-
yield {"type": "🧠 Thought", "content": "Both components extracted. Compiling division formula: 14000000 / 2100000."}
|
| 113 |
-
time.sleep(0.4)
|
| 114 |
-
|
| 115 |
-
yield {"type": "🔧 Action", "content": "Invoking Calculator tool with expression: [14000000 / 2100000]"}
|
| 116 |
-
time.sleep(0.3)
|
| 117 |
-
calc_res = self.tools["calculator"].execute("14000000 / 2100000")
|
| 118 |
-
yield {"type": "👁️ Observation", "content": calc_res}
|
| 119 |
-
time.sleep(0.4)
|
| 120 |
-
|
| 121 |
-
final_answer = "The relative population ratio of Tokyo to Paris is approximately 6.6667."
|
| 122 |
-
yield {"type": "✅ Final", "content": final_answer}
|
| 123 |
-
self.memory.add("assistant", final_answer)
|
| 124 |
-
|
| 125 |
-
class PlanExecuteAgent(BaseAgentLoop):
|
| 126 |
-
"""Macro Planning -> Isolated Execution -> Synthesized Aggregation"""
|
| 127 |
-
def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]:
|
| 128 |
-
self.memory.add("user", query)
|
| 129 |
-
|
| 130 |
-
yield {"type": "🧠 Thought", "content": f"Analyzing user intent: '{query}'. Creating immutable macro-execution plan."}
|
| 131 |
-
time.sleep(0.5)
|
| 132 |
-
|
| 133 |
-
plan = (
|
| 134 |
-
"1. Extract Tokyo demographics via Web_Search.\n"
|
| 135 |
-
"2. Extract Paris demographics via Web_Search.\n"
|
| 136 |
-
"3. Aggregate results and execute floating-point division using Calculator."
|
| 137 |
-
)
|
| 138 |
-
yield {"type": "📋 Plan Generated", "content": plan}
|
| 139 |
-
time.sleep(0.6)
|
| 140 |
-
|
| 141 |
-
yield {"type": "🔧 Action", "content": "Executing Step 1: Web_Search -> 'Tokyo population'"}
|
| 142 |
-
time.sleep(0.3)
|
| 143 |
-
t_res = self.tools["web_search"].execute("Tokyo")
|
| 144 |
-
yield {"type": "👁️ Observation", "content": t_res}
|
| 145 |
-
|
| 146 |
-
yield {"type": "🔧 Action", "content": "Executing Step 2: Web_Search -> 'Paris population'"}
|
| 147 |
-
time.sleep(0.3)
|
| 148 |
-
p_res = self.tools["web_search"].execute("Paris")
|
| 149 |
-
yield {"type": "👁️ Observation", "content": p_res}
|
| 150 |
-
time.sleep(0.4)
|
| 151 |
-
|
| 152 |
-
yield {"type": "🔧 Action", "content": "Executing Step 3: Math Evaluation -> '14000000 / 2100000'"}
|
| 153 |
-
time.sleep(0.3)
|
| 154 |
-
c_res = self.tools["calculator"].execute("14000000 / 2100000")
|
| 155 |
-
yield {"type": "👁️ Observation", "content": c_res}
|
| 156 |
-
time.sleep(0.4)
|
| 157 |
-
|
| 158 |
-
final_ans = "Plan executed perfectly. Synthesis: Tokyo's population scales 6.67x against Paris."
|
| 159 |
-
yield {"type": "✅ Final", "content": final_ans}
|
| 160 |
-
self.memory.add("assistant", final_ans)
|
| 161 |
-
|
| 162 |
-
class ReflectionAgent(BaseAgentLoop):
|
| 163 |
-
"""Self-Correction (Action -> Evaluation -> Self-Correction Loop)"""
|
| 164 |
-
def run_stream(self, query: str) -> Generator[Dict[str, str], None, None]:
|
| 165 |
-
self.memory.add("user", query)
|
| 166 |
-
|
| 167 |
-
yield {"type": "🧠 Thought", "content": "Attempting single-pass estimation for performance optimization."}
|
| 168 |
-
time.sleep(0.4)
|
| 169 |
-
|
| 170 |
-
yield {"type": "🔧 Action", "content": "Estimating quotient based on internal memory weights alone."}
|
| 171 |
-
time.sleep(0.3)
|
| 172 |
-
initial_guess = "Estimated Ratio: ~7.0 (Based on rough metadata markers)"
|
| 173 |
-
yield {"type": "👁️ Observation", "content": initial_guess}
|
| 174 |
-
time.sleep(0.4)
|
| 175 |
-
|
| 176 |
-
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."}
|
| 177 |
-
time.sleep(0.6)
|
| 178 |
-
|
| 179 |
-
yield {"type": "🔧 Action", "content": "Verifying Base Demographics -> Web_Search"}
|
| 180 |
-
time.sleep(0.3)
|
| 181 |
-
t_pop = self.tools["web_search"].execute("Tokyo")
|
| 182 |
-
p_pop = self.tools["web_search"].execute("Paris")
|
| 183 |
-
yield {"type": "👁️ Observation", "content": f"Verified Metrics: Tokyo={t_pop} | Paris={p_pop}"}
|
| 184 |
-
time.sleep(0.4)
|
| 185 |
-
|
| 186 |
-
yield {"type": "🔍 Self-Reflection", "content": "Data retrieved completely. Recalculating precisely to eliminate estimation drift."}
|
| 187 |
-
time.sleep(0.4)
|
| 188 |
-
|
| 189 |
-
yield {"type": "🔧 Action", "content": "Executing precise math -> Calculator"}
|
| 190 |
-
time.sleep(0.3)
|
| 191 |
-
c_res = self.tools["calculator"].execute("14000000/2100000")
|
| 192 |
-
yield {"type": "👁️ Observation", "content": c_res}
|
| 193 |
-
time.sleep(0.4)
|
| 194 |
-
|
| 195 |
-
final_ans = "Refined and validated outcome: Ratio optimized from 7.0 to precisely 6.6667."
|
| 196 |
-
yield {"type": "✅ Final", "content": final_ans}
|
| 197 |
-
self.memory.add("assistant", final_ans)
|
| 198 |
-
|
| 199 |
-
# =====================================================================
|
| 200 |
-
# 4. ORCHESTRATION ENGINE & INTERFACE
|
| 201 |
-
# =====================================================================
|
| 202 |
-
|
| 203 |
-
def orchestrate_single(architecture: str, query: str) -> Generator[str, None, None]:
|
| 204 |
-
memory = ShortTermMemory()
|
| 205 |
-
tools = [WebSearchTool(), CalculatorTool()]
|
| 206 |
-
|
| 207 |
-
if architecture == "ReAct (Reason + Act)":
|
| 208 |
-
agent = ReActAgent(tools, memory)
|
| 209 |
-
elif architecture == "Plan-Execute":
|
| 210 |
-
agent = PlanExecuteAgent(tools, memory)
|
| 211 |
-
else:
|
| 212 |
-
agent = ReflectionAgent(tools, memory)
|
| 213 |
-
|
| 214 |
-
log_stream = f"⚡ INITIALIZING AGENT: [{architecture}]\n{'='*50}\n\n"
|
| 215 |
-
yield log_stream
|
| 216 |
-
|
| 217 |
-
for step in agent.run_stream(query):
|
| 218 |
-
log_stream += f"[{step['type']}]\n➡️ {step['content']}\n\n{'-'*40}\n\n"
|
| 219 |
-
yield log_stream
|
| 220 |
-
|
| 221 |
-
def orchestrate_comparison(query: str) -> Generator[List[str], None, None]:
|
| 222 |
-
tools = [WebSearchTool(), CalculatorTool()]
|
| 223 |
-
react = ReActAgent(tools, ShortTermMemory())
|
| 224 |
-
plan = PlanExecuteAgent(tools, ShortTermMemory())
|
| 225 |
-
reflect = ReflectionAgent(tools, ShortTermMemory())
|
| 226 |
-
|
| 227 |
-
react_gen = react.run_stream(query)
|
| 228 |
-
plan_gen = plan.run_stream(query)
|
| 229 |
-
reflect_gen = reflect.run_stream(query)
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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