Cascade Bot commited on
Commit
3c2aa2f
·
1 Parent(s): bb6f0d3

Updated ChainOfThoughtStrategy to use StrategyResult and improved implementation

Browse files
Files changed (1) hide show
  1. 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
- "LOCAL_LLM": 0.8,
53
- "CHAIN_OF_THOUGHT": 0.6,
54
- "TREE_OF_THOUGHTS": 0.5,
55
- "META_LEARNING": 0.4
 
56
  }
57
- self.thought_history: List[Thought] = []
58
 
59
- async def reason(self, query: str, context: Dict[str, Any]) -> Dict[str, Any]:
60
- """Main reasoning method implementing chain of thought."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  try:
62
- # Initialize reasoning chain
63
- chain = await self._initialize_chain(query, context)
 
 
 
 
 
 
 
64
 
65
- # Generate initial thoughts
66
- thoughts = await self._generate_thoughts(query, context)
67
 
68
- # Build thought chain
69
- chain = await self._build_chain(thoughts, context)
 
 
 
 
 
 
70
 
71
  # Reflect and refine
72
- if self.enable_reflection:
73
- chain = await self._reflect_and_refine(chain, context)
 
74
 
75
- # Extract conclusion
76
- conclusion = await self._extract_conclusion(chain, context)
77
 
78
- # Update thought history
79
- self.thought_history.extend(chain)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"Error in chain of thought reasoning: {str(e)}")
92
- return {"success": False, "error": str(e)}
93
-
94
- async def _initialize_chain(self, query: str, context: Dict[str, Any]) -> List[Thought]:
95
- """Initialize the thought chain with observations."""
96
- prompt = f"""
97
- Initialize chain of thought for query:
98
- Query: {query}
99
- Context: {json.dumps(context)}
100
-
101
- Provide initial observations:
102
- 1. Key elements in query
103
- 2. Relevant context factors
104
- 3. Initial hypotheses
105
- 4. Potential approaches
106
-
107
- Format as:
108
- [O1] Element: ... | Relevance: ... | Confidence: ...
109
- [O2] Context: ... | Impact: ... | Confidence: ...
110
- [O3] Hypothesis: ... | Support: ... | Confidence: ...
111
- [O4] Approach: ... | Rationale: ... | Confidence: ...
112
- """
113
-
114
- response = await context["groq_api"].predict(prompt)
115
- return self._parse_observations(response["answer"])
116
-
117
- async def _generate_thoughts(self, query: str, context: Dict[str, Any]) -> List[Thought]:
118
- """Generate candidate thoughts for the chain."""
119
- prompt = f"""
120
- Generate thoughts for query analysis:
121
- Query: {query}
122
- Context: {json.dumps(context)}
123
-
124
- For each thought provide:
125
- 1. [Type]: {" | ".join([t.value for t in ThoughtType])}
126
- 2. [Content]: Main thought
127
- 3. [Evidence]: Supporting evidence
128
- 4. [Alternatives]: Alternative perspectives
129
- 5. [Next]: Potential next steps
130
- 6. [Confidence]: 0-1 score
131
-
132
- Format as:
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
- Format as:
189
- [Analysis]
190
- Gaps: ...
191
- Assumptions: ...
192
- Missing: ...
193
- Alternatives: ...
 
 
 
 
 
 
 
 
194
 
195
- [Refinements]
196
- Thoughts: ...
197
- Reasoning: ...
198
- Connections: ...
199
- Evidence: ...
200
- """
201
 
202
- response = await context["groq_api"].predict(prompt)
203
- return self._apply_refinements(chain, response["answer"])
204
-
205
- async def _extract_conclusion(self, chain: List[Thought], context: Dict[str, Any]) -> Dict[str, Any]:
206
- """Extract final conclusion from thought chain."""
207
- prompt = f"""
208
- Extract conclusion from thought chain:
209
- Chain: {json.dumps([self._thought_to_dict(t) for t in chain])}
210
- Context: {json.dumps(context)}
211
 
212
- Provide:
213
- 1. Main conclusion
214
- 2. Confidence level
215
- 3. Supporting evidence
216
- 4. Alternative conclusions
217
- 5. Meta-insights gained
218
- 6. Future considerations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
 
220
- Format as:
221
- [Conclusion]
222
- Answer: ...
223
- Confidence: ...
224
- Evidence: ...
225
- Alternatives: ...
226
 
227
- [Meta]
228
- Insights: ...
229
- Future: ...
230
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
- response = await context["groq_api"].predict(prompt)
233
- return self._parse_conclusion(response["answer"])
234
-
235
- def _parse_observations(self, response: str) -> List[Thought]:
236
- """Parse initial observations into thoughts."""
237
- observations = []
238
- lines = response.split('\n')
 
 
 
 
 
 
 
 
 
 
 
239
 
240
- for line in lines:
241
- if line.startswith('[O'):
242
- parts = line.split('|')
243
- if len(parts) >= 3:
244
- main_part = parts[0].split(']')[1].strip()
245
- key, content = main_part.split(':', 1)
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
- return observations
265
-
266
- def _parse_thoughts(self, response: str) -> List[Thought]:
267
- """Parse generated thoughts."""
268
- thoughts = []
269
- current = None
270
 
271
- for line in response.split('\n'):
272
- line = line.strip()
273
- if not line:
274
- continue
275
-
276
- if line.startswith('[T'):
277
- if current:
278
- thoughts.append(current)
279
- current = None
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
- if current:
311
- thoughts.append(current)
 
312
 
313
- return thoughts
314
-
315
- def _parse_chain(self, response: str, thoughts: List[Thought]) -> List[Thought]:
316
- """Parse and order thoughts into a chain."""
317
- chain = []
318
- thought_map = {self._thought_to_dict(t)["content"]: t for t in thoughts}
319
 
320
- for line in response.split('\n'):
321
- if line.startswith('Thought:'):
322
- content = line[8:].strip()
323
- if content in thought_map:
324
- chain.append(thought_map[content])
 
 
 
 
325
 
326
- return chain
327
-
328
- def _apply_refinements(self, chain: List[Thought], response: str) -> List[Thought]:
329
- """Apply refinements to thought chain."""
330
- refined_chain = chain.copy()
 
 
 
331
 
332
- # Parse refinements
333
- sections = response.split('[')
334
- for section in sections:
335
- if section.startswith('Refinements]'):
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 refined_chain
343
-
344
- def _parse_refinement_thoughts(self, refinements: str) -> List[Thought]:
345
- """Parse refinement thoughts."""
346
- thoughts = []
347
- for refinement in refinements.split(';'):
348
- if refinement.strip():
349
- thoughts.append(Thought(
350
- type=ThoughtType.REFINEMENT,
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
- sections = response.split('[')
372
- for section in sections:
373
- if section.startswith('Conclusion]'):
374
- lines = section.split('\n')[1:]
375
- for line in lines:
376
- if line.startswith('Answer:'):
377
- conclusion["answer"] = line[7:].strip()
378
- elif line.startswith('Confidence:'):
379
- try:
380
- conclusion["confidence"] = float(line[11:].strip())
381
- except:
382
- conclusion["confidence"] = 0.5
383
- elif line.startswith('Evidence:'):
384
- conclusion["evidence"] = [e.strip() for e in line[9:].split(',')]
385
- elif line.startswith('Alternatives:'):
386
- conclusion["alternatives"] = [a.strip() for a in line[13:].split(',')]
387
- elif section.startswith('Meta]'):
388
- lines = section.split('\n')[1:]
389
- for line in lines:
390
- if line.startswith('Insights:'):
391
- conclusion["meta_insights"] = [i.strip() for i in line[9:].split(',')]
392
- elif line.startswith('Future:'):
393
- conclusion["future_considerations"] = [f.strip() for f in line[7:].split(',')]
 
394
 
395
- return conclusion
396
-
397
- def _thought_to_dict(self, thought: Thought) -> Dict[str, Any]:
398
- """Convert thought to dictionary for serialization."""
 
 
 
 
399
  return {
400
- "type": thought.type.value,
401
- "content": thought.content,
402
- "confidence": thought.confidence,
403
- "evidence": thought.evidence,
404
- "alternatives": thought.alternatives,
405
- "next_steps": thought.next_steps,
406
- "metadata": thought.metadata
407
  }
408
-
409
- def get_thought_history(self) -> List[Dict[str, Any]]:
410
- """Get the history of all thoughts processed."""
411
- return [self._thought_to_dict(t) for t in self.thought_history]
412
-
413
- def clear_history(self) -> None:
414
- """Clear thought history."""
415
- self.thought_history = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ })