Spaces:
Runtime error
Runtime error
Cascade Bot
commited on
Commit
·
3c2aa2f
1
Parent(s):
bb6f0d3
Updated ChainOfThoughtStrategy to use StrategyResult and improved implementation
Browse files- reasoning/chain_of_thought.py +359 -334
reasoning/chain_of_thought.py
CHANGED
|
@@ -5,8 +5,9 @@ from typing import Dict, Any, List, Optional, Tuple
|
|
| 5 |
import json
|
| 6 |
from dataclasses import dataclass
|
| 7 |
from enum import Enum
|
|
|
|
| 8 |
|
| 9 |
-
from .base import ReasoningStrategy
|
| 10 |
|
| 11 |
class ThoughtType(Enum):
|
| 12 |
"""Types of thoughts in the chain."""
|
|
@@ -28,6 +29,7 @@ class Thought:
|
|
| 28 |
alternatives: List[str]
|
| 29 |
next_steps: List[str]
|
| 30 |
metadata: Dict[str, Any]
|
|
|
|
| 31 |
|
| 32 |
class ChainOfThoughtStrategy(ReasoningStrategy):
|
| 33 |
"""
|
|
@@ -45,371 +47,394 @@ class ChainOfThoughtStrategy(ReasoningStrategy):
|
|
| 45 |
parallel_threshold: int = 3,
|
| 46 |
learning_rate: float = 0.1,
|
| 47 |
strategy_weights: Optional[Dict[str, float]] = None):
|
|
|
|
|
|
|
| 48 |
self.min_confidence = min_confidence
|
| 49 |
self.parallel_threshold = parallel_threshold
|
| 50 |
self.learning_rate = learning_rate
|
| 51 |
self.strategy_weights = strategy_weights or {
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
|
|
|
| 56 |
}
|
| 57 |
-
self.thought_history: List[Thought] = []
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
try:
|
| 62 |
-
#
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
# Generate
|
| 66 |
-
|
| 67 |
|
| 68 |
-
#
|
| 69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
# Reflect and refine
|
| 72 |
-
if self.
|
| 73 |
-
|
|
|
|
| 74 |
|
| 75 |
-
#
|
| 76 |
-
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
-
return {
|
| 82 |
-
"success": True,
|
| 83 |
-
"answer": conclusion["answer"],
|
| 84 |
-
"confidence": conclusion["confidence"],
|
| 85 |
-
"reasoning_chain": [self._thought_to_dict(t) for t in chain],
|
| 86 |
-
"alternatives": conclusion["alternatives"],
|
| 87 |
-
"evidence": conclusion["evidence"],
|
| 88 |
-
"meta_insights": conclusion["meta_insights"]
|
| 89 |
-
}
|
| 90 |
except Exception as e:
|
| 91 |
-
logging.error(f"
|
| 92 |
-
return
|
| 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 |
-
[T1]
|
| 134 |
-
Type: ...
|
| 135 |
-
Content: ...
|
| 136 |
-
Evidence: ...
|
| 137 |
-
Alternatives: ...
|
| 138 |
-
Next: ...
|
| 139 |
-
Confidence: ...
|
| 140 |
-
"""
|
| 141 |
-
|
| 142 |
-
response = await context["groq_api"].predict(prompt)
|
| 143 |
-
return self._parse_thoughts(response["answer"])
|
| 144 |
-
|
| 145 |
-
async def _build_chain(self, thoughts: List[Thought], context: Dict[str, Any]) -> List[Thought]:
|
| 146 |
-
"""Build coherent chain from candidate thoughts."""
|
| 147 |
-
prompt = f"""
|
| 148 |
-
Build coherent thought chain:
|
| 149 |
-
Thoughts: {json.dumps([self._thought_to_dict(t) for t in thoughts])}
|
| 150 |
-
Context: {json.dumps(context)}
|
| 151 |
-
|
| 152 |
-
For each step specify:
|
| 153 |
-
1. Selected thought
|
| 154 |
-
2. Reasoning for selection
|
| 155 |
-
3. Connection to previous
|
| 156 |
-
4. Expected impact
|
| 157 |
-
|
| 158 |
-
Format as:
|
| 159 |
-
[S1]
|
| 160 |
-
Thought: ...
|
| 161 |
-
Reason: ...
|
| 162 |
-
Connection: ...
|
| 163 |
-
Impact: ...
|
| 164 |
-
"""
|
| 165 |
-
|
| 166 |
-
response = await context["groq_api"].predict(prompt)
|
| 167 |
-
return self._parse_chain(response["answer"], thoughts)
|
| 168 |
-
|
| 169 |
-
async def _reflect_and_refine(self, chain: List[Thought], context: Dict[str, Any]) -> List[Thought]:
|
| 170 |
-
"""Reflect on and refine the thought chain."""
|
| 171 |
-
prompt = f"""
|
| 172 |
-
Reflect on thought chain:
|
| 173 |
-
Chain: {json.dumps([self._thought_to_dict(t) for t in chain])}
|
| 174 |
-
Context: {json.dumps(context)}
|
| 175 |
-
|
| 176 |
-
Analyze for:
|
| 177 |
-
1. Logical gaps
|
| 178 |
-
2. Weak assumptions
|
| 179 |
-
3. Missing evidence
|
| 180 |
-
4. Alternative perspectives
|
| 181 |
-
|
| 182 |
-
Suggest refinements:
|
| 183 |
-
1. Additional thoughts
|
| 184 |
-
2. Modified reasoning
|
| 185 |
-
3. New connections
|
| 186 |
-
4. Evidence needs
|
| 187 |
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
Reasoning: ...
|
| 198 |
-
Connections: ...
|
| 199 |
-
Evidence: ...
|
| 200 |
-
"""
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
Chain: {json.dumps([self._thought_to_dict(t) for t in chain])}
|
| 210 |
-
Context: {json.dumps(context)}
|
| 211 |
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
-
|
| 221 |
-
[Conclusion]
|
| 222 |
-
Answer: ...
|
| 223 |
-
Confidence: ...
|
| 224 |
-
Evidence: ...
|
| 225 |
-
Alternatives: ...
|
| 226 |
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
evidence = [p.strip() for p in parts[1].split(':')[1].strip().split(',')]
|
| 248 |
-
|
| 249 |
-
try:
|
| 250 |
-
confidence = float(parts[2].split(':')[1].strip())
|
| 251 |
-
except:
|
| 252 |
-
confidence = 0.5
|
| 253 |
-
|
| 254 |
-
observations.append(Thought(
|
| 255 |
-
type=ThoughtType.OBSERVATION,
|
| 256 |
-
content=content.strip(),
|
| 257 |
-
confidence=confidence,
|
| 258 |
-
evidence=evidence,
|
| 259 |
-
alternatives=[],
|
| 260 |
-
next_steps=[],
|
| 261 |
-
metadata={"key": key}
|
| 262 |
-
))
|
| 263 |
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
"""Parse generated thoughts."""
|
| 268 |
-
thoughts = []
|
| 269 |
-
current = None
|
| 270 |
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
elif line.startswith('Type:'):
|
| 281 |
-
type_str = line[5:].strip()
|
| 282 |
-
try:
|
| 283 |
-
thought_type = ThoughtType(type_str.lower())
|
| 284 |
-
current = Thought(
|
| 285 |
-
type=thought_type,
|
| 286 |
-
content="",
|
| 287 |
-
confidence=0.0,
|
| 288 |
-
evidence=[],
|
| 289 |
-
alternatives=[],
|
| 290 |
-
next_steps=[],
|
| 291 |
-
metadata={}
|
| 292 |
-
)
|
| 293 |
-
except ValueError:
|
| 294 |
-
logging.warning(f"Invalid thought type: {type_str}")
|
| 295 |
-
elif current:
|
| 296 |
-
if line.startswith('Content:'):
|
| 297 |
-
current.content = line[8:].strip()
|
| 298 |
-
elif line.startswith('Evidence:'):
|
| 299 |
-
current.evidence = [e.strip() for e in line[9:].split(',')]
|
| 300 |
-
elif line.startswith('Alternatives:'):
|
| 301 |
-
current.alternatives = [a.strip() for a in line[13:].split(',')]
|
| 302 |
-
elif line.startswith('Next:'):
|
| 303 |
-
current.next_steps = [n.strip() for n in line[5:].split(',')]
|
| 304 |
-
elif line.startswith('Confidence:'):
|
| 305 |
-
try:
|
| 306 |
-
current.confidence = float(line[11:].strip())
|
| 307 |
-
except:
|
| 308 |
-
current.confidence = 0.5
|
| 309 |
|
| 310 |
-
|
| 311 |
-
|
|
|
|
| 312 |
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
chain = []
|
| 318 |
-
thought_map = {self._thought_to_dict(t)["content"]: t for t in thoughts}
|
| 319 |
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 325 |
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
|
|
|
|
|
|
|
|
|
| 331 |
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
lines = section.split('\n')[1:]
|
| 337 |
-
for line in lines:
|
| 338 |
-
if line.startswith('Thoughts:'):
|
| 339 |
-
new_thoughts = self._parse_refinement_thoughts(line[9:])
|
| 340 |
-
refined_chain.extend(new_thoughts)
|
| 341 |
|
| 342 |
-
return
|
| 343 |
-
|
| 344 |
-
def
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
content=refinement.strip(),
|
| 352 |
-
confidence=0.8, # Refinements typically have high confidence
|
| 353 |
-
evidence=[],
|
| 354 |
-
alternatives=[],
|
| 355 |
-
next_steps=[],
|
| 356 |
-
metadata={"refined": True}
|
| 357 |
-
))
|
| 358 |
-
return thoughts
|
| 359 |
-
|
| 360 |
-
def _parse_conclusion(self, response: str) -> Dict[str, Any]:
|
| 361 |
-
"""Parse final conclusion."""
|
| 362 |
-
conclusion = {
|
| 363 |
-
"answer": "",
|
| 364 |
-
"confidence": 0.0,
|
| 365 |
-
"evidence": [],
|
| 366 |
-
"alternatives": [],
|
| 367 |
-
"meta_insights": [],
|
| 368 |
-
"future_considerations": []
|
| 369 |
-
}
|
| 370 |
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
|
|
|
| 394 |
|
| 395 |
-
return
|
| 396 |
-
|
| 397 |
-
def
|
| 398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
return {
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
"alternatives": thought.alternatives,
|
| 405 |
-
"next_steps": thought.next_steps,
|
| 406 |
-
"metadata": thought.metadata
|
| 407 |
}
|
| 408 |
-
|
| 409 |
-
def
|
| 410 |
-
"""
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import json
|
| 6 |
from dataclasses import dataclass
|
| 7 |
from enum import Enum
|
| 8 |
+
from datetime import datetime
|
| 9 |
|
| 10 |
+
from .base import ReasoningStrategy, StrategyResult
|
| 11 |
|
| 12 |
class ThoughtType(Enum):
|
| 13 |
"""Types of thoughts in the chain."""
|
|
|
|
| 29 |
alternatives: List[str]
|
| 30 |
next_steps: List[str]
|
| 31 |
metadata: Dict[str, Any]
|
| 32 |
+
timestamp: str = datetime.now().isoformat()
|
| 33 |
|
| 34 |
class ChainOfThoughtStrategy(ReasoningStrategy):
|
| 35 |
"""
|
|
|
|
| 47 |
parallel_threshold: int = 3,
|
| 48 |
learning_rate: float = 0.1,
|
| 49 |
strategy_weights: Optional[Dict[str, float]] = None):
|
| 50 |
+
"""Initialize Chain of Thought reasoning."""
|
| 51 |
+
super().__init__()
|
| 52 |
self.min_confidence = min_confidence
|
| 53 |
self.parallel_threshold = parallel_threshold
|
| 54 |
self.learning_rate = learning_rate
|
| 55 |
self.strategy_weights = strategy_weights or {
|
| 56 |
+
'observation': 0.2,
|
| 57 |
+
'analysis': 0.3,
|
| 58 |
+
'hypothesis': 0.2,
|
| 59 |
+
'verification': 0.15,
|
| 60 |
+
'conclusion': 0.15
|
| 61 |
}
|
|
|
|
| 62 |
|
| 63 |
+
# Initialize thought chain
|
| 64 |
+
self.thoughts: List[Thought] = []
|
| 65 |
+
|
| 66 |
+
# Performance tracking
|
| 67 |
+
self.performance_metrics = {
|
| 68 |
+
'avg_confidence': 0.0,
|
| 69 |
+
'chain_length': 0,
|
| 70 |
+
'refinement_count': 0,
|
| 71 |
+
'parallel_paths': 0
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
async def reason(
|
| 75 |
+
self,
|
| 76 |
+
query: str,
|
| 77 |
+
context: Dict[str, Any]
|
| 78 |
+
) -> StrategyResult:
|
| 79 |
+
"""
|
| 80 |
+
Apply Chain of Thought reasoning to analyze the query.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
query: The input query to reason about
|
| 84 |
+
context: Additional context and parameters
|
| 85 |
+
|
| 86 |
+
Returns:
|
| 87 |
+
StrategyResult containing the reasoning chain and confidence
|
| 88 |
+
"""
|
| 89 |
try:
|
| 90 |
+
# Reset thought chain
|
| 91 |
+
self.thoughts = []
|
| 92 |
+
|
| 93 |
+
# Initial observation
|
| 94 |
+
await self._add_thought(
|
| 95 |
+
ThoughtType.OBSERVATION,
|
| 96 |
+
f"Analyzing query: {query}",
|
| 97 |
+
context
|
| 98 |
+
)
|
| 99 |
|
| 100 |
+
# Generate analysis thoughts
|
| 101 |
+
await self._analyze_query(query, context)
|
| 102 |
|
| 103 |
+
# Generate hypotheses
|
| 104 |
+
hypotheses = await self._generate_hypotheses(context)
|
| 105 |
+
|
| 106 |
+
# Verify hypotheses
|
| 107 |
+
await self._verify_hypotheses(hypotheses, context)
|
| 108 |
+
|
| 109 |
+
# Draw conclusions
|
| 110 |
+
conclusion = await self._draw_conclusion(context)
|
| 111 |
|
| 112 |
# Reflect and refine
|
| 113 |
+
if conclusion.confidence < self.min_confidence:
|
| 114 |
+
await self._reflect_and_refine(context)
|
| 115 |
+
conclusion = await self._draw_conclusion(context)
|
| 116 |
|
| 117 |
+
# Update performance metrics
|
| 118 |
+
self._update_metrics()
|
| 119 |
|
| 120 |
+
return StrategyResult(
|
| 121 |
+
strategy_type="chain_of_thought",
|
| 122 |
+
success=True,
|
| 123 |
+
answer=conclusion.content,
|
| 124 |
+
confidence=conclusion.confidence,
|
| 125 |
+
reasoning_trace=[{
|
| 126 |
+
"step": str(t.type.value),
|
| 127 |
+
"content": t.content,
|
| 128 |
+
"confidence": t.confidence,
|
| 129 |
+
"evidence": t.evidence,
|
| 130 |
+
"alternatives": t.alternatives,
|
| 131 |
+
"next_steps": t.next_steps,
|
| 132 |
+
"metadata": t.metadata,
|
| 133 |
+
"timestamp": t.timestamp
|
| 134 |
+
} for t in self.thoughts],
|
| 135 |
+
metadata={
|
| 136 |
+
"num_thoughts": len(self.thoughts),
|
| 137 |
+
"thought_types": [t.type.value for t in self.thoughts],
|
| 138 |
+
"final_confidence": conclusion.confidence
|
| 139 |
+
},
|
| 140 |
+
performance_metrics=self.performance_metrics
|
| 141 |
+
)
|
| 142 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
except Exception as e:
|
| 144 |
+
logging.error(f"Chain of Thought reasoning error: {str(e)}")
|
| 145 |
+
return StrategyResult(
|
| 146 |
+
strategy_type="chain_of_thought",
|
| 147 |
+
success=False,
|
| 148 |
+
answer=None,
|
| 149 |
+
confidence=0.0,
|
| 150 |
+
reasoning_trace=[{
|
| 151 |
+
"step": "error",
|
| 152 |
+
"error": str(e),
|
| 153 |
+
"timestamp": datetime.now().isoformat()
|
| 154 |
+
}],
|
| 155 |
+
metadata={"error": str(e)},
|
| 156 |
+
performance_metrics=self.performance_metrics
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
async def _add_thought(
|
| 160 |
+
self,
|
| 161 |
+
type: ThoughtType,
|
| 162 |
+
content: str,
|
| 163 |
+
context: Dict[str, Any]
|
| 164 |
+
) -> Thought:
|
| 165 |
+
"""Add a new thought to the chain."""
|
| 166 |
+
thought = Thought(
|
| 167 |
+
type=type,
|
| 168 |
+
content=content,
|
| 169 |
+
confidence=self._calculate_confidence(content, context),
|
| 170 |
+
evidence=self._gather_evidence(content, context),
|
| 171 |
+
alternatives=self._generate_alternatives(content, context),
|
| 172 |
+
next_steps=self._determine_next_steps(type, context),
|
| 173 |
+
metadata=self._extract_metadata(content, context)
|
| 174 |
+
)
|
| 175 |
+
self.thoughts.append(thought)
|
| 176 |
+
return thought
|
| 177 |
+
|
| 178 |
+
async def _analyze_query(
|
| 179 |
+
self,
|
| 180 |
+
query: str,
|
| 181 |
+
context: Dict[str, Any]
|
| 182 |
+
) -> None:
|
| 183 |
+
"""Generate analysis thoughts."""
|
| 184 |
+
# Extract key components
|
| 185 |
+
components = self._extract_components(query)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
+
# Analyze each component
|
| 188 |
+
for comp in components:
|
| 189 |
+
await self._add_thought(
|
| 190 |
+
ThoughtType.ANALYSIS,
|
| 191 |
+
f"Analysis of {comp}: {self._analyze_component(comp, context)}",
|
| 192 |
+
context
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
async def _generate_hypotheses(
|
| 196 |
+
self,
|
| 197 |
+
context: Dict[str, Any]
|
| 198 |
+
) -> List[Thought]:
|
| 199 |
+
"""Generate hypothesis thoughts."""
|
| 200 |
+
hypotheses = []
|
| 201 |
|
| 202 |
+
# Generate hypotheses based on analysis
|
| 203 |
+
analysis_thoughts = [t for t in self.thoughts if t.type == ThoughtType.ANALYSIS]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
+
for analysis in analysis_thoughts:
|
| 206 |
+
hypothesis = await self._add_thought(
|
| 207 |
+
ThoughtType.HYPOTHESIS,
|
| 208 |
+
f"Based on {analysis.content}, hypothesis: {self._generate_hypothesis(analysis, context)}",
|
| 209 |
+
context
|
| 210 |
+
)
|
| 211 |
+
hypotheses.append(hypothesis)
|
|
|
|
|
|
|
| 212 |
|
| 213 |
+
return hypotheses
|
| 214 |
+
|
| 215 |
+
async def _verify_hypotheses(
|
| 216 |
+
self,
|
| 217 |
+
hypotheses: List[Thought],
|
| 218 |
+
context: Dict[str, Any]
|
| 219 |
+
) -> None:
|
| 220 |
+
"""Verify generated hypotheses."""
|
| 221 |
+
for hypothesis in hypotheses:
|
| 222 |
+
await self._add_thought(
|
| 223 |
+
ThoughtType.VERIFICATION,
|
| 224 |
+
f"Verifying {hypothesis.content}: {self._verify_hypothesis(hypothesis, context)}",
|
| 225 |
+
context
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
async def _draw_conclusion(
|
| 229 |
+
self,
|
| 230 |
+
context: Dict[str, Any]
|
| 231 |
+
) -> Thought:
|
| 232 |
+
"""Draw conclusion from verified hypotheses."""
|
| 233 |
+
verified_thoughts = [t for t in self.thoughts if t.type == ThoughtType.VERIFICATION]
|
| 234 |
|
| 235 |
+
conclusion_content = self._synthesize_conclusion(verified_thoughts, context)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 236 |
|
| 237 |
+
return await self._add_thought(
|
| 238 |
+
ThoughtType.CONCLUSION,
|
| 239 |
+
conclusion_content,
|
| 240 |
+
context
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
async def _reflect_and_refine(
|
| 244 |
+
self,
|
| 245 |
+
context: Dict[str, Any]
|
| 246 |
+
) -> None:
|
| 247 |
+
"""Reflect on the reasoning chain and refine if needed."""
|
| 248 |
+
# Add reflection thought
|
| 249 |
+
reflection = await self._add_thought(
|
| 250 |
+
ThoughtType.REFLECTION,
|
| 251 |
+
self._generate_reflection(self.thoughts, context),
|
| 252 |
+
context
|
| 253 |
+
)
|
| 254 |
|
| 255 |
+
# Add refinement if needed
|
| 256 |
+
if reflection.confidence < self.min_confidence:
|
| 257 |
+
await self._add_thought(
|
| 258 |
+
ThoughtType.REFINEMENT,
|
| 259 |
+
self._generate_refinement(reflection, context),
|
| 260 |
+
context
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
self.performance_metrics['refinement_count'] += 1
|
| 264 |
+
|
| 265 |
+
def _calculate_confidence(
|
| 266 |
+
self,
|
| 267 |
+
content: str,
|
| 268 |
+
context: Dict[str, Any]
|
| 269 |
+
) -> float:
|
| 270 |
+
"""Calculate confidence score for a thought."""
|
| 271 |
+
# Base confidence
|
| 272 |
+
confidence = 0.5
|
| 273 |
|
| 274 |
+
# Adjust based on content length and complexity
|
| 275 |
+
words = content.split()
|
| 276 |
+
if len(words) > 50:
|
| 277 |
+
confidence += 0.1
|
| 278 |
+
if len(words) > 100:
|
| 279 |
+
confidence += 0.1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
+
# Adjust based on evidence
|
| 282 |
+
evidence = self._gather_evidence(content, context)
|
| 283 |
+
confidence += min(0.3, len(evidence) * 0.1)
|
|
|
|
|
|
|
|
|
|
| 284 |
|
| 285 |
+
return min(1.0, confidence)
|
| 286 |
+
|
| 287 |
+
def _gather_evidence(
|
| 288 |
+
self,
|
| 289 |
+
content: str,
|
| 290 |
+
context: Dict[str, Any]
|
| 291 |
+
) -> List[str]:
|
| 292 |
+
"""Gather evidence supporting the thought."""
|
| 293 |
+
evidence = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
+
# Extract from context
|
| 296 |
+
if 'evidence' in context:
|
| 297 |
+
evidence.extend(context['evidence'])
|
| 298 |
|
| 299 |
+
# Extract from previous thoughts
|
| 300 |
+
for thought in self.thoughts:
|
| 301 |
+
if any(term in thought.content.lower() for term in content.lower().split()):
|
| 302 |
+
evidence.append(f"Supported by previous thought: {thought.content}")
|
|
|
|
|
|
|
| 303 |
|
| 304 |
+
return evidence
|
| 305 |
+
|
| 306 |
+
def _generate_alternatives(
|
| 307 |
+
self,
|
| 308 |
+
content: str,
|
| 309 |
+
context: Dict[str, Any]
|
| 310 |
+
) -> List[str]:
|
| 311 |
+
"""Generate alternative perspectives."""
|
| 312 |
+
alternatives = []
|
| 313 |
|
| 314 |
+
# Generate opposites
|
| 315 |
+
words = content.lower().split()
|
| 316 |
+
opposites = {
|
| 317 |
+
'increase': 'decrease',
|
| 318 |
+
'high': 'low',
|
| 319 |
+
'good': 'bad',
|
| 320 |
+
'positive': 'negative'
|
| 321 |
+
}
|
| 322 |
|
| 323 |
+
for word in words:
|
| 324 |
+
if word in opposites:
|
| 325 |
+
alt = content.replace(word, opposites[word])
|
| 326 |
+
alternatives.append(f"Alternative: {alt}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
|
| 328 |
+
return alternatives
|
| 329 |
+
|
| 330 |
+
def _determine_next_steps(
|
| 331 |
+
self,
|
| 332 |
+
type: ThoughtType,
|
| 333 |
+
context: Dict[str, Any]
|
| 334 |
+
) -> List[str]:
|
| 335 |
+
"""Determine possible next steps."""
|
| 336 |
+
steps = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
|
| 338 |
+
if type == ThoughtType.OBSERVATION:
|
| 339 |
+
steps.extend([
|
| 340 |
+
"Analyze key components",
|
| 341 |
+
"Identify patterns",
|
| 342 |
+
"Consider context"
|
| 343 |
+
])
|
| 344 |
+
elif type == ThoughtType.ANALYSIS:
|
| 345 |
+
steps.extend([
|
| 346 |
+
"Generate hypotheses",
|
| 347 |
+
"Look for correlations",
|
| 348 |
+
"Consider alternatives"
|
| 349 |
+
])
|
| 350 |
+
elif type == ThoughtType.HYPOTHESIS:
|
| 351 |
+
steps.extend([
|
| 352 |
+
"Verify hypothesis",
|
| 353 |
+
"Gather evidence",
|
| 354 |
+
"Test assumptions"
|
| 355 |
+
])
|
| 356 |
+
elif type == ThoughtType.VERIFICATION:
|
| 357 |
+
steps.extend([
|
| 358 |
+
"Draw conclusions",
|
| 359 |
+
"Consider implications",
|
| 360 |
+
"Plan actions"
|
| 361 |
+
])
|
| 362 |
|
| 363 |
+
return steps
|
| 364 |
+
|
| 365 |
+
def _extract_metadata(
|
| 366 |
+
self,
|
| 367 |
+
content: str,
|
| 368 |
+
context: Dict[str, Any]
|
| 369 |
+
) -> Dict[str, Any]:
|
| 370 |
+
"""Extract metadata from thought content."""
|
| 371 |
return {
|
| 372 |
+
'length': len(content),
|
| 373 |
+
'complexity': len(content.split()),
|
| 374 |
+
'context_keys': list(context.keys()),
|
| 375 |
+
'timestamp': datetime.now().isoformat()
|
|
|
|
|
|
|
|
|
|
| 376 |
}
|
| 377 |
+
|
| 378 |
+
def _extract_components(self, query: str) -> List[str]:
|
| 379 |
+
"""Extract key components from query."""
|
| 380 |
+
# Simple word-based extraction
|
| 381 |
+
# Could be enhanced with NLP
|
| 382 |
+
return [w.strip() for w in query.split() if len(w.strip()) > 3]
|
| 383 |
+
|
| 384 |
+
def _analyze_component(
|
| 385 |
+
self,
|
| 386 |
+
component: str,
|
| 387 |
+
context: Dict[str, Any]
|
| 388 |
+
) -> str:
|
| 389 |
+
"""Analyze a single component."""
|
| 390 |
+
return f"Component {component} analysis based on context"
|
| 391 |
+
|
| 392 |
+
def _generate_hypothesis(
|
| 393 |
+
self,
|
| 394 |
+
analysis: Thought,
|
| 395 |
+
context: Dict[str, Any]
|
| 396 |
+
) -> str:
|
| 397 |
+
"""Generate hypothesis from analysis."""
|
| 398 |
+
return f"Hypothesis generated from {analysis.content}"
|
| 399 |
+
|
| 400 |
+
def _verify_hypothesis(
|
| 401 |
+
self,
|
| 402 |
+
hypothesis: Thought,
|
| 403 |
+
context: Dict[str, Any]
|
| 404 |
+
) -> str:
|
| 405 |
+
"""Verify a hypothesis."""
|
| 406 |
+
return f"Verification of {hypothesis.content}"
|
| 407 |
+
|
| 408 |
+
def _synthesize_conclusion(
|
| 409 |
+
self,
|
| 410 |
+
verified_thoughts: List[Thought],
|
| 411 |
+
context: Dict[str, Any]
|
| 412 |
+
) -> str:
|
| 413 |
+
"""Synthesize conclusion from verified thoughts."""
|
| 414 |
+
return "Conclusion based on verified thoughts: " + \
|
| 415 |
+
", ".join(t.content for t in verified_thoughts)
|
| 416 |
+
|
| 417 |
+
def _generate_reflection(
|
| 418 |
+
self,
|
| 419 |
+
thoughts: List[Thought],
|
| 420 |
+
context: Dict[str, Any]
|
| 421 |
+
) -> str:
|
| 422 |
+
"""Generate reflection on thought chain."""
|
| 423 |
+
return f"Reflection on {len(thoughts)} thoughts in chain"
|
| 424 |
+
|
| 425 |
+
def _generate_refinement(
|
| 426 |
+
self,
|
| 427 |
+
reflection: Thought,
|
| 428 |
+
context: Dict[str, Any]
|
| 429 |
+
) -> str:
|
| 430 |
+
"""Generate refinement based on reflection."""
|
| 431 |
+
return f"Refinement based on {reflection.content}"
|
| 432 |
+
|
| 433 |
+
def _update_metrics(self) -> None:
|
| 434 |
+
"""Update performance metrics."""
|
| 435 |
+
if self.thoughts:
|
| 436 |
+
self.performance_metrics.update({
|
| 437 |
+
'avg_confidence': sum(t.confidence for t in self.thoughts) / len(self.thoughts),
|
| 438 |
+
'chain_length': len(self.thoughts),
|
| 439 |
+
'parallel_paths': len([t for t in self.thoughts if t.alternatives])
|
| 440 |
+
})
|