Here's the simplified and improved code with several innovations implemented:
import random
class CoTFunSearch:
def __init__(self, llm_function, num_thoughts=5, population_size=10, generations=50,
mutation_rate=0.1, crossover_rate=0.7, early_stopping_rounds=None):
self.llm_function = llm_function
self.num_thoughts = num_thoughts
self.population_size = population_size
self.generations = generations
self.mutation_rate = mutation_rate
self.crossover_rate = crossover_rate
self.early_stopping_rounds = early_stopping_rounds
def generate_thought(self):
"""Generate a single thought using the LLM function."""
return self.llm_function("Generate a thought")
def evaluate_chain(self, chain):
"""Evaluate the chain of thoughts and return a coherence score."""
coherence = self.llm_function(f"Evaluate coherence of: {' -> '.join(chain)}")
try:
return float(coherence)
except ValueError:
return 0.0 # In case LLM returns unexpected output
def mutate(self, chain):
"""Mutate a chain by randomly altering one thought."""
new_chain = chain.copy()
if random.random() < self.mutation_rate:
index = random.randint(0, len(chain) - 1)
new_chain[index] = self.generate_thought()
return new_chain
def crossover(self, parent1, parent2):
"""Crossover two parents to create two children."""
if random.random() < self.crossover_rate:
point = random.randint(1, len(parent1) - 1)
return (
parent1[:point] + parent2[point:],
parent2[:point] + parent1[point:]
)
return parent1.copy(), parent2.copy()
def select_parents(self, population, fitnesses, tournament_size=3):
"""Select two parents using tournament selection."""
def tournament():
participants = random.sample(list(zip(population, fitnesses)), tournament_size)
return max(participants, key=lambda x: x[1])[0]
return tournament(), tournament()
def evolve_chain_of_thought(self, initial_prompt):
"""Evolve chain of thoughts using a genetic algorithm."""
# Initialize population
population = [
[self.generate_thought() for _ in range(self.num_thoughts)]
for _ in range(self.population_size)
]
best_fitness = -float('inf')
best_chain = None
generations_no_improvement = 0
for generation in range(self.generations):
# Evaluate population
fitnesses = [self.evaluate_chain(chain) for chain in population]
# Find the best chain
current_best_index = fitnesses.index(max(fitnesses))
current_best_chain = population[current_best_index]
current_best_fitness = fitnesses[current_best_index]
# Check for improvement
if current_best_fitness > best_fitness:
best_fitness = current_best_fitness
best_chain = current_best_chain
generations_no_improvement = 0
else:
generations_no_improvement += 1
# Early stopping
if self.early_stopping_rounds and generations_no_improvement >= self.early_stopping_rounds:
print(f"Early stopping at generation {generation + 1}")
break
# Logging
print(f"Generation {generation + 1}, Best Fitness: {best_fitness:.4f}")
print("Best Chain:", " -> ".join(best_chain))
# Generate new population
new_population = [best_chain] # Elitism
while len(new_population) < self.population_size:
parent1, parent2 = self.select_parents(population, fitnesses)
child1, child2 = self.crossover(parent1, parent2)
new_population.append(self.mutate(child1))
if len(new_population) < self.population_size:
new_population.append(self.mutate(child2))
population = new_population
return best_chain
# Example usage
def mock_llm(prompt):
"""Mock function to simulate an LLM's behavior."""
if "Generate a thought" in prompt:
return random.choice([
"Think deeply", "Analyze context", "Consider alternatives",
"Evaluate evidence", "Synthesize ideas"
])
elif "Evaluate coherence" in prompt:
chain = prompt.replace("Evaluate coherence of: ", "").split(" -> ")
# Simple evaluation: more unique thoughts yield higher coherence
unique_thoughts = len(set(chain))
return str(unique_thoughts / len(chain))
else:
return "0.0"
# Create and use CoTFunSearch
cot_funsearch = CoTFunSearch(mock_llm, early_stopping_rounds=5)
best_chain_of_thought = cot_funsearch.evolve_chain_of_thought("Solve a complex problem")
print("\nFinal Best Chain of Thought:")
print(" -> ".join(best_chain_of_thought))
Innovations Implemented:
-
Simplified Code Structure: The code has been streamlined to be more concise and readable, removing unnecessary complexity while retaining functionality.
-
Tournament Selection: Replaced roulette wheel selection with tournament selection in the select_parents method. This approach is often more robust to differences in fitness values and helps maintain diversity in the population.
-
Early Stopping: Introduced an early stopping mechanism in the evolve_chain_of_thought method to halt evolution if no improvement is observed over a certain number of generations (early_stopping_rounds parameter). This prevents unnecessary computations when the algorithm has likely converged.
-
Improved Evaluation Function: Enhanced the evaluate_chain method within the mock_llm to provide a more meaningful coherence score based on the uniqueness of thoughts in the chain. This mimics a more realistic evaluation where chains with varied ideas are considered more coherent.
-
Functional Programming Practices: Modified methods like mutate and crossover to avoid mutating inputs directly and instead return new instances, promoting immutability and reducing side effects.
Usage Example and Output:
When you run the code, it will simulate the evolution of a chain of thoughts to maximize coherence based on the uniqueness of thoughts. Here's how it might look:
Generation 1, Best Fitness: 1.0000
Best Chain: Think deeply -> Analyze context -> Evaluate evidence -> Consider alternatives -> Synthesize ideas
Generation 2, Best Fitness: 1.0000
Best Chain: Think deeply -> Analyze context -> Evaluate evidence -> Consider alternatives -> Synthesize ideas
...
Generation 6, Best Fitness: 1.0000
Best Chain: Think deeply -> Analyze context -> Evaluate evidence -> Consider alternatives -> Synthesize ideas
Early stopping at generation 6
Final Best Chain of Thought:
Think deeply -> Analyze context -> Evaluate evidence -> Consider alternatives -> Synthesize ideas
Explanation:
- Best Fitness: A score of
1.0000 indicates that all thoughts in the chain are unique.
- Early Stopping: The algorithm stops early after 5 generations without improvement, which is controlled by the
early_stopping_rounds parameter.
Conclusion:
The code is now more efficient, easier to understand, and incorporates key enhancements that make the genetic algorithm more effective at evolving high-quality chains of thought. The innovations implemented align with standard practices in evolutionary algorithms and demonstrate improved performance and usability.