PYAE1994 commited on
Commit
597ccbf
·
verified ·
1 Parent(s): e8fb14a

God Mode+ v3 fix: agents/reasoning_agent.py

Browse files
Files changed (1) hide show
  1. agents/reasoning_agent.py +21 -287
agents/reasoning_agent.py CHANGED
@@ -1,296 +1,30 @@
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
25
- - Mathematical reasoning
26
- - Logical analysis
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",
286
- "Problem decomposition",
287
- "Mathematical reasoning",
288
- "Logical analysis",
289
- "Strategic planning",
290
- ],
291
- "reasoning_depth": self.reasoning_depth,
292
- "max_reasoning_tokens": self.max_reasoning_tokens,
293
- }
294
-
295
-
296
- __all__ = ["ReasoningAgent"]
 
1
  """
2
+ ReasoningAgent Deep reasoning tasks via LLMRouter
 
 
3
  """
 
 
 
 
 
4
  import structlog
5
+ from typing import Dict
6
+ from .base_agent import BaseAgent
7
 
8
  log = structlog.get_logger()
9
 
10
+ REASONING_SYSTEM = """You are an expert analytical reasoner.
11
+ Think step-by-step, consider multiple perspectives, and provide well-structured, logical responses.
12
+ For complex problems, use chain-of-thought reasoning."""
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ class ReasoningAgent(BaseAgent):
16
+ def __init__(self, ws_manager=None, ai_router=None):
17
+ super().__init__("ReasoningAgent", ws_manager, ai_router)
18
+
19
+ async def run(self, task: str, context: Dict = {}, **kwargs) -> str:
20
+ session_id = kwargs.get("session_id", context.get("session_id", ""))
21
+ task_id = kwargs.get("task_id", context.get("task_id", ""))
22
+ messages = [
23
+ {"role": "system", "content": REASONING_SYSTEM},
24
+ {"role": "user", "content": f"Think carefully and reason through this:\n\n{task}"},
25
+ ]
26
+ await self.emit(task_id, "reasoning_started", {"task": task[:100]}, session_id)
27
+ return await self.ask_llm(
28
+ messages=messages, task_id=task_id, session_id=session_id,
29
+ temperature=0.5, max_tokens=8192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  )