God Agent CI commited on
Commit
a65f14f
·
1 Parent(s): 8001a61

fix: Python 3.11 compat - debug_agent f-string + reasoning_agent import

Browse files

- Fixed debug_agent.py: Removed backslash from f-string expressions (Python 3.11 doesn't allow backslash in f-string expressions before 3.12)
- Fixed reasoning_agent.py: Changed incorrect import 'from core.agent import BaseAgent' to 'from .base_agent import BaseAgent'
- Fixed reasoning_agent.py: Updated __init__ and run() to match BaseAgent interface
- These fixes were blocking HF Space deployment (RUNTIME_ERROR -> RUNNING)

backend/agents/debug_agent.py CHANGED
@@ -44,12 +44,12 @@ class DebugAgent(BaseAgent):
44
  messages = [
45
  {"role": "system", "content": DEBUG_SYSTEM},
46
  {"role": "user", "content": (
47
- f"Debug and fix this issue (attempt {attempt}):\n\n"
48
- f"{task}\n\n"
49
- f"Provide:\n"
50
- f"1. Root cause analysis\n"
51
- f"2. Exact fix (code/config)\n"
52
- f"3. Prevention strategy"
53
  )},
54
  ]
55
 
@@ -71,14 +71,19 @@ class DebugAgent(BaseAgent):
71
 
72
  async def analyze_error(self, error_output: str, source_code: str = "", task_id: str = "", session_id: str = "") -> Dict:
73
  """Deep error analysis with structured output."""
 
 
 
 
 
74
  messages = [
75
  {"role": "system", "content": DEBUG_SYSTEM},
76
  {"role": "user", "content": (
77
- f"Analyze this error and provide structured diagnosis:\n\n"
78
- f"Error:\n{error_output[:2000]}\n\n"
79
- f"{'Source Code:\\n```\\n' + source_code[:1000] + '\\n```' if source_code else ''}\n\n"
80
- f"Respond with JSON:\n"
81
- f'{{"error_type": "...", "root_cause": "...", "fix": "...", "prevention": "...", "severity": "low|medium|high|critical"}}'
82
  )},
83
  ]
84
  raw = await self.llm(messages, task_id=task_id, session_id=session_id, temperature=0.1, max_tokens=1000)
@@ -111,10 +116,10 @@ class DebugAgent(BaseAgent):
111
  messages = [
112
  {"role": "system", "content": DEBUG_SYSTEM},
113
  {"role": "user", "content": (
114
- f"Fix attempt {attempt}/{max_retries}:\n\n"
115
- f"Error: {current_error}\n\n"
116
- f"Code:\n```\n{current_code[:3000]}\n```\n\n"
117
- f"Return ONLY the fixed code."
118
  )},
119
  ]
120
 
@@ -143,7 +148,7 @@ class DebugAgent(BaseAgent):
143
  compile(code, "<string>", "exec")
144
  return {"valid": True, "error": ""}
145
  except SyntaxError as e:
146
- return {"valid": False, "error": f"SyntaxError: {e}"}
147
  except Exception as e:
148
  return {"valid": False, "error": str(e)}
149
 
 
44
  messages = [
45
  {"role": "system", "content": DEBUG_SYSTEM},
46
  {"role": "user", "content": (
47
+ "Debug and fix this issue (attempt " + str(attempt) + "):\n\n"
48
+ + task + "\n\n"
49
+ "Provide:\n"
50
+ "1. Root cause analysis\n"
51
+ "2. Exact fix (code/config)\n"
52
+ "3. Prevention strategy"
53
  )},
54
  ]
55
 
 
71
 
72
  async def analyze_error(self, error_output: str, source_code: str = "", task_id: str = "", session_id: str = "") -> Dict:
73
  """Deep error analysis with structured output."""
74
+ if source_code:
75
+ source_section = "Source Code:\n```\n" + source_code[:1000] + "\n```"
76
+ else:
77
+ source_section = ""
78
+
79
  messages = [
80
  {"role": "system", "content": DEBUG_SYSTEM},
81
  {"role": "user", "content": (
82
+ "Analyze this error and provide structured diagnosis:\n\n"
83
+ "Error:\n" + error_output[:2000] + "\n\n"
84
+ + source_section + "\n\n"
85
+ "Respond with JSON:\n"
86
+ '{"error_type": "...", "root_cause": "...", "fix": "...", "prevention": "...", "severity": "low|medium|high|critical"}'
87
  )},
88
  ]
89
  raw = await self.llm(messages, task_id=task_id, session_id=session_id, temperature=0.1, max_tokens=1000)
 
116
  messages = [
117
  {"role": "system", "content": DEBUG_SYSTEM},
118
  {"role": "user", "content": (
119
+ "Fix attempt " + str(attempt) + "/" + str(max_retries) + ":\n\n"
120
+ "Error: " + current_error + "\n\n"
121
+ "Code:\n```\n" + current_code[:3000] + "\n```\n\n"
122
+ "Return ONLY the fixed code."
123
  )},
124
  ]
125
 
 
148
  compile(code, "<string>", "exec")
149
  return {"valid": True, "error": ""}
150
  except SyntaxError as e:
151
+ return {"valid": False, "error": "SyntaxError: " + str(e)}
152
  except Exception as e:
153
  return {"valid": False, "error": str(e)}
154
 
backend/agents/reasoning_agent.py CHANGED
@@ -1,24 +1,34 @@
1
  """
2
- 🚀 GOD MODE+ v3 - Reasoning Agent
3
- Specialized agent for complex reasoning tasks using DeepSeek R1, Qwen QwQ, o1-mini
4
- Version: 3.0.0
5
  """
6
 
7
  import asyncio
8
  import json
9
- from typing import Dict, Any, Optional
10
 
11
  import structlog
12
 
13
- from core.agent import BaseAgent
14
 
15
  log = structlog.get_logger()
16
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  class ReasoningAgent(BaseAgent):
19
  """
20
  Specialized agent for complex reasoning, analysis, and problem-solving tasks.
21
-
22
  Capabilities:
23
  - Multi-step reasoning with chain-of-thought
24
  - Complex problem decomposition
@@ -27,259 +37,127 @@ class ReasoningAgent(BaseAgent):
27
  - Strategic planning
28
  """
29
 
30
- def __init__(self, ws_manager, ai_router):
31
- """Initialize Reasoning Agent."""
32
- super().__init__(
33
- name="ReasoningAgent",
34
- color="🟦",
35
- description="Complex reasoning and analysis",
36
- ws_manager=ws_manager,
37
- ai_router=ai_router,
38
- )
39
- self.reasoning_depth = 3 # Number of reasoning steps
40
  self.max_reasoning_tokens = 16000
41
 
42
- async def process(self, task: Dict[str, Any]) -> Dict[str, Any]:
43
- """
44
- Process reasoning task with multi-step reasoning.
45
- """
46
- user_message = task.get("content", "")
47
- session_id = task.get("session_id", "")
48
- context = task.get("context", {})
49
 
50
- log.info("🧠 Reasoning Agent activated", message=user_message[:100])
 
 
 
51
 
52
  try:
53
  # Step 1: Analyze the problem
54
- analysis = await self._analyze_problem(user_message, context)
55
- await self._broadcast(session_id, {
56
- "type": "reasoning_step",
57
- "step": "analysis",
58
- "data": analysis,
59
- })
60
-
61
- # Step 2: Break down into sub-problems
62
- sub_problems = await self._decompose_problem(user_message, analysis)
63
- await self._broadcast(session_id, {
64
- "type": "reasoning_step",
65
- "step": "decomposition",
66
- "data": sub_problems,
67
- })
68
-
69
- # Step 3: Solve each sub-problem
70
- solutions = []
71
- for i, sub_problem in enumerate(sub_problems):
72
- solution = await self._solve_sub_problem(sub_problem, context)
73
- solutions.append(solution)
74
- await self._broadcast(session_id, {
75
- "type": "reasoning_step",
76
- "step": f"solution_{i+1}",
77
- "data": solution,
78
- })
79
-
80
- # Step 4: Synthesize final answer
81
- final_answer = await self._synthesize_answer(
82
- user_message,
83
- analysis,
84
- sub_problems,
85
- solutions
86
- )
87
-
88
- await self._broadcast(session_id, {
89
- "type": "reasoning_complete",
90
- "answer": final_answer,
91
  "reasoning_depth": self.reasoning_depth,
92
- })
93
 
94
- return {
95
- "success": True,
96
- "agent": self.name,
97
- "answer": final_answer,
98
- "reasoning_steps": {
99
- "analysis": analysis,
100
- "sub_problems": sub_problems,
101
- "solutions": solutions,
102
- },
103
- }
104
 
105
  except Exception as e:
106
- log.error(" Reasoning Agent failed", error=str(e))
107
- return {
108
- "success": False,
109
- "agent": self.name,
110
- "error": str(e),
111
- }
112
-
113
- async def _analyze_problem(self, problem: str, context: Dict[str, Any]) -> Dict[str, Any]:
114
- """
115
- Analyze the problem using reasoning model.
116
- """
117
- prompt = f"""Analyze this problem and identify:
118
- 1. Core problem statement
119
- 2. Key constraints
120
- 3. Required information
121
- 4. Potential approaches
122
-
123
- Problem: {problem}
124
-
125
- Provide structured analysis."""
126
-
127
- response = await self.ai_router.route(
128
- prompt,
129
- context={"task_type": "reasoning"},
130
- optimize_for="quality"
131
- )
132
-
133
- return {
134
- "problem_type": self._classify_problem(problem),
135
- "complexity": self._estimate_complexity(problem),
136
- "analysis": response.get("response", ""),
137
- }
138
-
139
- async def _decompose_problem(
140
- self,
141
- problem: str,
142
- analysis: Dict[str, Any]
143
- ) -> list:
144
- """
145
- Break down complex problem into manageable sub-problems.
146
- """
147
- prompt = f"""Based on this analysis, break down the problem into 3-5 specific sub-problems:
148
-
149
- Problem: {problem}
150
- Analysis: {json.dumps(analysis, indent=2)}
151
-
152
- List each sub-problem clearly and explain the dependencies."""
153
-
154
- response = await self.ai_router.route(
155
- prompt,
156
- context={"task_type": "reasoning"},
157
- optimize_for="quality"
158
  )
159
 
160
- # Parse sub-problems from response
161
- sub_problems = self._parse_sub_problems(response.get("response", ""))
162
- return sub_problems
163
-
164
- async def _solve_sub_problem(
165
- self,
166
- sub_problem: str,
167
- context: Dict[str, Any]
168
- ) -> Dict[str, Any]:
169
- """
170
- Solve individual sub-problem.
171
- """
172
- prompt = f"""Solve this sub-problem step by step:
173
-
174
- {sub_problem}
175
-
176
- Provide:
177
- 1. Step-by-step solution
178
- 2. Key insights
179
- 3. Confidence level (0-100)"""
180
-
181
- response = await self.ai_router.route(
182
- prompt,
183
- context={"task_type": "reasoning"},
184
- optimize_for="quality"
185
- )
186
 
187
- return {
188
- "sub_problem": sub_problem,
189
- "solution": response.get("response", ""),
190
- "model_used": response.get("model", "unknown"),
191
- }
 
 
192
 
193
  async def _synthesize_answer(
194
  self,
195
- original_problem: str,
196
- analysis: Dict[str, Any],
197
- sub_problems: list,
198
- solutions: list
 
 
199
  ) -> str:
200
- """
201
- Synthesize final answer from all reasoning steps.
202
- """
203
- synthesis_prompt = f"""Based on the analysis and solutions, provide a comprehensive answer:
204
-
205
- Original Problem: {original_problem}
206
-
207
- Analysis: {json.dumps(analysis, indent=2)}
208
-
209
- Solutions:
210
- {json.dumps(solutions, indent=2)}
211
-
212
- Provide a clear, well-reasoned final answer that:
213
- 1. Directly addresses the original problem
214
- 2. Integrates insights from all sub-problems
215
- 3. Explains the reasoning clearly
216
- 4. Suggests any follow-up actions if needed"""
217
-
218
- response = await self.ai_router.route(
219
- synthesis_prompt,
220
- context={"task_type": "reasoning"},
221
- optimize_for="quality"
222
  )
223
-
224
- return response.get("response", "Unable to synthesize answer")
225
-
226
- def _classify_problem(self, problem: str) -> str:
227
- """Classify problem type."""
228
- problem_lower = problem.lower()
229
-
230
- if any(word in problem_lower for word in ["math", "calculate", "equation"]):
231
- return "mathematical"
232
- elif any(word in problem_lower for word in ["logic", "reason", "why"]):
233
- return "logical"
234
- elif any(word in problem_lower for word in ["plan", "strategy", "approach"]):
235
- return "strategic"
236
- elif any(word in problem_lower for word in ["analyze", "compare", "evaluate"]):
237
- return "analytical"
238
- else:
239
- return "general"
240
-
241
- def _estimate_complexity(self, problem: str) -> str:
242
- """Estimate problem complexity."""
243
- word_count = len(problem.split())
244
-
245
- if word_count < 20:
246
- return "simple"
247
- elif word_count < 100:
248
- return "moderate"
249
- else:
250
- return "complex"
251
-
252
- def _parse_sub_problems(self, response: str) -> list:
253
- """Parse sub-problems from model response."""
254
- # Simple parsing - can be enhanced
255
- lines = response.split("\n")
256
- sub_problems = []
257
-
258
- for line in lines:
259
- line = line.strip()
260
- if line and any(line.startswith(f"{i}.") for i in range(1, 10)):
261
- sub_problems.append(line)
262
-
263
- return sub_problems if sub_problems else [response]
264
-
265
- async def _broadcast(self, session_id: str, data: Dict[str, Any]):
266
- """Broadcast reasoning progress to client."""
267
- if self.ws_manager:
268
- await self.ws_manager.broadcast(
269
- room=f"chat:{session_id}",
270
- message={
271
- "type": "agent_message",
272
- "agent": self.name,
273
- "color": self.color,
274
- **data,
275
- }
276
- )
277
 
278
  def get_status(self) -> Dict[str, Any]:
279
  """Get agent status."""
280
  return {
281
  "name": self.name,
282
- "color": self.color,
283
  "status": "ready",
284
  "capabilities": [
285
  "Multi-step reasoning",
@@ -289,7 +167,6 @@ Provide a clear, well-reasoned final answer that:
289
  "Strategic planning",
290
  ],
291
  "reasoning_depth": self.reasoning_depth,
292
- "max_reasoning_tokens": self.max_reasoning_tokens,
293
  }
294
 
295
 
 
1
  """
2
+ ReasoningAgent v7 Complex reasoning, analysis, and multi-step problem solving
3
+ GOD AGENT OS Using DeepSeek R1, Qwen QwQ, o1-mini style reasoning
 
4
  """
5
 
6
  import asyncio
7
  import json
8
+ from typing import Dict, Any, List, Optional
9
 
10
  import structlog
11
 
12
+ from .base_agent import BaseAgent
13
 
14
  log = structlog.get_logger()
15
 
16
+ REASONING_SYSTEM = """You are an elite autonomous reasoning and analysis agent.
17
+ You excel at:
18
+ - Multi-step reasoning with chain-of-thought
19
+ - Complex problem decomposition and analysis
20
+ - Mathematical and logical reasoning
21
+ - Strategic planning and decision making
22
+ - Root cause analysis
23
+
24
+ Always think step by step, show your reasoning, and provide confident conclusions.
25
+ """
26
+
27
 
28
  class ReasoningAgent(BaseAgent):
29
  """
30
  Specialized agent for complex reasoning, analysis, and problem-solving tasks.
31
+
32
  Capabilities:
33
  - Multi-step reasoning with chain-of-thought
34
  - Complex problem decomposition
 
37
  - Strategic planning
38
  """
39
 
40
+ def __init__(self, ws_manager=None, ai_router=None):
41
+ super().__init__("ReasoningAgent", ws_manager, ai_router)
42
+ self.reasoning_depth = 3
 
 
 
 
 
 
 
43
  self.max_reasoning_tokens = 16000
44
 
45
+ async def run(self, task: str, context: Dict = {}, **kwargs) -> str:
46
+ """Execute reasoning task."""
47
+ session_id = kwargs.get("session_id", "")
48
+ task_id = kwargs.get("task_id", "")
 
 
 
49
 
50
+ await self.emit(task_id, "agent_start", {
51
+ "agent": "ReasoningAgent",
52
+ "task": task[:80],
53
+ }, session_id)
54
 
55
  try:
56
  # Step 1: Analyze the problem
57
+ analysis = await self._analyze_problem(task, context, task_id, session_id)
58
+
59
+ # Step 2: Decompose if complex
60
+ if len(task.split()) > 30:
61
+ sub_problems = await self._decompose_problem(task, analysis, task_id, session_id)
62
+ solutions = []
63
+ for sub in sub_problems[:3]:
64
+ sol = await self._solve_sub_problem(sub, context, task_id, session_id)
65
+ solutions.append(sol)
66
+ result = await self._synthesize_answer(task, analysis, sub_problems, solutions, task_id, session_id)
67
+ else:
68
+ result = analysis
69
+
70
+ await self.emit(task_id, "reasoning_complete", {
71
+ "agent": "ReasoningAgent",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  "reasoning_depth": self.reasoning_depth,
73
+ }, session_id)
74
 
75
+ return result
 
 
 
 
 
 
 
 
 
76
 
77
  except Exception as e:
78
+ log.error("ReasoningAgent failed", error=str(e))
79
+ return "Reasoning agent encountered an error: " + str(e)
80
+
81
+ async def _analyze_problem(self, problem: str, context: Dict, task_id: str, session_id: str) -> str:
82
+ """Analyze the problem using reasoning model."""
83
+ messages = [
84
+ {"role": "system", "content": REASONING_SYSTEM},
85
+ {"role": "user", "content": (
86
+ "Analyze this problem step by step:\n\n"
87
+ + problem + "\n\n"
88
+ "Provide:\n"
89
+ "1. Problem type and complexity\n"
90
+ "2. Key constraints and requirements\n"
91
+ "3. Step-by-step solution\n"
92
+ "4. Final answer/recommendation"
93
+ )},
94
+ ]
95
+ return await self.llm(
96
+ messages,
97
+ task_id=task_id,
98
+ session_id=session_id,
99
+ temperature=0.2,
100
+ max_tokens=self.max_reasoning_tokens,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  )
102
 
103
+ async def _decompose_problem(self, problem: str, analysis: str, task_id: str, session_id: str) -> List[str]:
104
+ """Break down complex problem into sub-problems."""
105
+ messages = [
106
+ {"role": "system", "content": REASONING_SYSTEM},
107
+ {"role": "user", "content": (
108
+ "Break this complex problem into 3 specific sub-problems:\n\n"
109
+ + problem + "\n\n"
110
+ "Initial analysis: " + analysis[:500] + "\n\n"
111
+ "List each sub-problem on a new line starting with '1.', '2.', '3.'"
112
+ )},
113
+ ]
114
+ raw = await self.llm(messages, task_id=task_id, session_id=session_id, temperature=0.3, max_tokens=2000)
115
+ # Parse numbered sub-problems
116
+ lines = raw.split("\n")
117
+ sub_problems = []
118
+ for line in lines:
119
+ line = line.strip()
120
+ if line and any(line.startswith(str(i) + ".") for i in range(1, 10)):
121
+ sub_problems.append(line)
122
+ return sub_problems if sub_problems else [problem]
 
 
 
 
 
 
123
 
124
+ async def _solve_sub_problem(self, sub_problem: str, context: Dict, task_id: str, session_id: str) -> str:
125
+ """Solve individual sub-problem."""
126
+ messages = [
127
+ {"role": "system", "content": REASONING_SYSTEM},
128
+ {"role": "user", "content": "Solve this specific problem:\n\n" + sub_problem},
129
+ ]
130
+ return await self.llm(messages, task_id=task_id, session_id=session_id, temperature=0.2, max_tokens=4096)
131
 
132
  async def _synthesize_answer(
133
  self,
134
+ original: str,
135
+ analysis: str,
136
+ sub_problems: List[str],
137
+ solutions: List[str],
138
+ task_id: str,
139
+ session_id: str,
140
  ) -> str:
141
+ """Synthesize final answer from all reasoning steps."""
142
+ solutions_text = "\n".join(
143
+ "Sub-problem " + str(i + 1) + ": " + sol[:300]
144
+ for i, sol in enumerate(solutions)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  )
146
+ messages = [
147
+ {"role": "system", "content": REASONING_SYSTEM},
148
+ {"role": "user", "content": (
149
+ "Original problem: " + original + "\n\n"
150
+ "Analysis: " + analysis[:800] + "\n\n"
151
+ "Solutions to sub-problems:\n" + solutions_text + "\n\n"
152
+ "Provide a comprehensive final answer that integrates all insights."
153
+ )},
154
+ ]
155
+ return await self.llm(messages, task_id=task_id, session_id=session_id, temperature=0.3, max_tokens=8192)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
  def get_status(self) -> Dict[str, Any]:
158
  """Get agent status."""
159
  return {
160
  "name": self.name,
 
161
  "status": "ready",
162
  "capabilities": [
163
  "Multi-step reasoning",
 
167
  "Strategic planning",
168
  ],
169
  "reasoning_depth": self.reasoning_depth,
 
170
  }
171
 
172