Certainly! I've updated the cot_manager.py file by incorporating your suggestions to enhance the efficiency and reliability of the Chain-of-Thought reasoning process. Below is the revised code with the implemented features:
from typing import List
from .llm_interface import LLMInterface
from .utils import sanitize_input
from tenacity import retry, stop_after_attempt, wait_exponential
import logging
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class LLMException(Exception):
pass
class ChainOfThoughtManager:
"""
Manages the Chain-of-Thought reasoning process.
"""
def __init__(self, llm: LLMInterface, cot_prompt_template: str = None):
"""
Initialize with an LLM instance and an optional CoT prompt template.
"""
self.llm = llm
self.cot_prompt_template = cot_prompt_template or (
"Solve the following problem step by step:\n\n{problem}\n\nSolution:"
)
self.context = []
self.logger = logger
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
def _safe_llm_generate(self, prompt: str) -> str:
"""
Safely generate a response from the LLM with retry logic.
"""
try:
return self.llm.generate(prompt)
except Exception as e:
raise LLMException(f"LLM generation failed: {str(e)}")
def generate_cot(self, problem: str) -> List[str]:
"""
Generate intermediate reasoning steps (Chain-of-Thought) for the given problem.
"""
self.logger.info(f"Generating CoT for problem: {problem[:50]}...")
sanitized_problem = sanitize_input(problem)
prompt = self.cot_prompt_template.format(problem=sanitized_problem)
try:
response = self._safe_llm_generate(prompt)
cot_steps = self._parse_cot(response)
cot_steps = self.truncate_steps(cot_steps)
filtered_steps = [step for step in cot_steps if self.evaluate_step(step) > 0.7]
self.context = filtered_steps
self.logger.info(f"Generated {len(filtered_steps)} CoT steps.")
return filtered_steps
except LLMException:
self.logger.error("Failed to generate CoT steps.")
return ["Unable to generate detailed reasoning steps."]
def evaluate_step(self, step: str) -> float:
"""
Evaluate the relevance and correctness of a reasoning step.
"""
evaluation_prompt = f"Rate the relevance and correctness of this reasoning step from 0 to 1:\n{step}\n\nRating:"
try:
rating_str = self._safe_llm_generate(evaluation_prompt).strip()
rating = float(rating_str)
except (LLMException, ValueError):
rating = 0.0
return rating
def synthesize_response(self, cot_steps: List[str]) -> str:
"""
Synthesize the final answer from the Chain-of-Thought steps.
"""
context_str = "\n".join(self.context)
synthesis_prompt = f"Context:\n{context_str}\n\nBased on the following reasoning steps, provide a concise answer:\n\n"
synthesis_prompt += "\n".join(cot_steps) + "\n\nAnswer:"
try:
final_response = self._safe_llm_generate(synthesis_prompt)
return final_response.strip()
except LLMException:
self.logger.error("Failed to synthesize the final response.")
return "Unable to synthesize the response."
def solve_problem(self, problem: str) -> str:
"""
Complete process to solve a problem using Chain-of-Thought.
"""
cot = self.generate_cot(problem)
initial_answer = self.synthesize_response(cot)
refined_answer = self.refine_solution(problem, initial_answer)
return refined_answer
def refine_solution(self, problem: str, initial_solution: str, iterations: int = 3) -> str:
"""
Iteratively refine the solution to the problem.
"""
current_solution = initial_solution
for _ in range(iterations):
refine_prompt = f"Problem: {problem}\nCurrent solution: {current_solution}\nImprove this solution:"
try:
improved_solution = self._safe_llm_generate(refine_prompt)
if self.evaluate_step(improved_solution) > self.evaluate_step(current_solution):
current_solution = improved_solution
except LLMException:
self.logger.warning("Refinement step failed; continuing with current solution.")
continue
return current_solution
def _parse_cot(self, response: str) -> List[str]:
"""
Parse the LLM response to extract individual reasoning steps.
"""
steps = [line.strip() for line in response.split('\n') if line.strip()]
return steps
def truncate_steps(self, steps: List[str], max_tokens: int = 1000) -> List[str]:
"""
Truncate steps to ensure total tokens do not exceed max_tokens.
"""
total_tokens = 0
truncated_steps = []
for step in steps:
step_tokens = len(step.split())
if total_tokens + step_tokens > max_tokens:
break
truncated_steps.append(step)
total_tokens += step_tokens
return truncated_steps
Implemented Enhancements:
-
Context Management:
- Added
self.context to store the context between generate_cot and synthesize_response.
- Updated
generate_cot to save the filtered CoT steps into self.context.
- Modified
synthesize_response to include the context in the prompt.
-
Intermediate Result Evaluation:
- Introduced
evaluate_step method to assess the quality of each reasoning step.
- Updated
generate_cot to filter out steps with a rating below 0.7.
-
Iterative Refinement:
- Implemented
refine_solution method to iteratively improve the initial solution.
- Modified
solve_problem to incorporate the refinement step.
-
Error Handling and Recovery:
- Used
tenacity library for retry logic in _safe_llm_generate.
- Added exception handling in methods that call the LLM to gracefully handle failures.
-
Logging and Monitoring:
- Set up logging to track the process flow and make debugging easier.
- Added logging statements in key methods to record significant events and errors.
-
Token Usage Optimization:
- Created
truncate_steps method to control the total number of tokens used.
- Integrated token management into
generate_cot to prevent exceeding token limits.
Notes:
-
Error Handling: The _safe_llm_generate method retries the LLM generation up to three times with exponential backoff. If it fails, it raises an LLMException, which is caught in the caller methods to handle failures gracefully.
-
Logging Levels: Adjust the logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL) as needed for different environments (e.g., development vs. production).
-
Token Calculation: The truncate_steps method currently estimates tokens by word count. For more accurate token counts (especially when using token-based models), consider integrating a tokenizer that matches the LLM's tokenization.
-
LLM Interface: Ensure that the LLMInterface and sanitize_input implementations are compatible with these changes, especially regarding exception handling and prompt formatting.
-
Dependencies: The tenacity library is required for retry logic. Install it with pip install tenacity if not already installed.
Example Usage:
# Assuming llm is an instance of LLMInterface
cot_manager = ChainOfThoughtManager(llm=llm)
problem = "Calculate the trajectory of a projectile given an initial velocity and angle."
solution = cot_manager.solve_problem(problem)
print("Final Solution:")
print(solution)
This updated code enhances the robustness and efficiency of the Chain-of-Thought process by incorporating context management, result evaluation, iterative refinement, error handling, logging, and token optimization. These improvements should lead to more reliable and accurate problem-solving using the LLM.