Generate step-by-step reasoning paths and synthetic training data for AI models
from praisonaiagents import Agentagent = Agent( name="Reasoner", instructions="Show step-by-step reasoning before the final answer.",)agent.start("If a train travels 60 mph for 2.5 hours, how far does it go?")
The user poses a multi-step problem; the agent records chain-of-thought steps before answering.
The Chain-of-Thought (CoT) tools enable AI agents to generate step-by-step reasoning paths for problem-solving and create synthetic reasoning data for training purposes. These tools help break down complex problems into manageable steps and document the reasoning process.
from praisonaiagents import Agentagent = Agent( name="ReasoningAgent", instructions="Think step by step before answering.", reasoning=True,)agent.start("If a train travels 60 mph for 2.5 hours, how far does it go?")
Chain-of-Thought reasoning is a technique where AI models explicitly show their step-by-step thinking process when solving problems. This approach improves accuracy, provides transparency, and generates valuable training data for improving AI models.
Saves chain-of-thought solutions to a CSV file for further analysis or training data generation.
from praisonaiagents import cot_save# Save reasoning datacot_save( input_data="Solve: If a train travels 120 miles in 2 hours, what is its average speed?", output_data={ "step1": "Identify given information: distance = 120 miles, time = 2 hours", "step2": "Apply formula: speed = distance / time", "step3": "Calculate: speed = 120 miles / 2 hours = 60 mph", "answer": "60 miles per hour" }, filename="reasoning_examples.csv")
from praisonaiagents import Agent, Taskfrom praisonaiagents import cot_save# Create a reasoning agentreasoning_agent = Agent( name="Reasoning Agent", instructions="""You are an expert at breaking down complex problems into steps. For each problem, provide: 1. Problem understanding 2. Step-by-step solution 3. Final answer 4. Verification""", tools=[cot_save])# Create a tasktask = Task( description="Solve this problem step-by-step: A bakery sells 120 cookies per day. If they're open 6 days a week, how many cookies do they sell in 4 weeks?", agent=reasoning_agent)# Execute - note: Tasks are run via agents.start() or agent.start()result = reasoning_agent.start(task.description)
from praisonaiagents import Agent, Task, AgentTeamfrom praisonaiagents import cot_save, cot_upload_to_huggingface# Problem decomposer agentdecomposer = Agent( name="Problem Decomposer", instructions="Break down complex problems into smaller sub-problems", tools=[cot_save])# Step solver agentsolver = Agent( name="Step Solver", instructions="Solve each sub-problem step by step", tools=[cot_save])# Verifier agentverifier = Agent( name="Solution Verifier", instructions="Verify the solution and check for errors", tools=[cot_save])# Tasksdecompose_task = Task( description="Break down: How many different 5-card poker hands contain exactly 3 aces?", agent=decomposer)solve_task = Task( description="Solve each sub-problem identified", agent=solver)verify_task = Task( description="Verify the solution using a different approach", agent=verifier)# Run with Agentsreasoning_agents = AgentTeam( agents=[decomposer, solver, verifier], tasks=[decompose_task, solve_task, verify_task])result = reasoning_agents.start()
from praisonaiagents import cot_saveimport pandas as pd# Process multiple problems in batchproblems = [ "Calculate 15% of 240", "Find the area of a circle with radius 7", "Convert 72°F to Celsius"]for problem in problems: # Generate reasoning for each problem reasoning_steps = generate_reasoning(problem) # Your reasoning function # Save each solution cot_save( input_data=problem, output_data=reasoning_steps, filename="batch_reasoning.csv" )# Upload complete datasetcot_upload_to_huggingface( dataset_path="batch_reasoning.csv", dataset_name="math-reasoning-dataset")
# Prepare data for model trainingdef prepare_for_training(csv_path, output_format='jsonl'): df = pd.read_csv(csv_path) training_data = [] for _, row in df.iterrows(): entry = { 'instruction': row['input'], 'reasoning': row['output'], 'model_type': 'chain-of-thought' } training_data.append(entry) # Save in training format if output_format == 'jsonl': import json with open('training_data.jsonl', 'w') as f: for item in training_data: f.write(json.dumps(item) + '\n') return training_data
The GenerateCOT class requires Q&A pairs to be provided upfront. It does not generate questions automatically.
from praisonaiagents.tools.train.data.generatecot import GenerateCOT# Define Q&A pairsqa_pairs = { "What is 15% of 80?": "12", "If a car travels 60 mph for 2.5 hours, how far does it go?": "150 miles", "What is the area of a rectangle with length 8 and width 5?": "40"}# Initialize GenerateCOTcot_gen = GenerateCOT( qa_pairs=qa_pairs, model="gpt-4o-mini", temperature=0.7, max_attempts=3, verbose=True)# Generate solutions for each questionfor question in qa_pairs: # Generate solution with thought process solution_dict = cot_gen.cot_run_dict(question) print(f"Question: {question}") print(f"Thought Process: {solution_dict.get('thought_process')}") print(f"Final Answer: {solution_dict.get('final_answer')}") print("-" * 50)
# Export to JSON with Q&A pairscot_gen.cot_export_json_with_qa_pairs( filepath='cot_dataset.json', save_to_file=True)# Export to CSVcot_gen.cot_export_csv_with_qa_pairs( filepath='cot_dataset.csv')# Save individual Q&A paircot_gen.cot_save( question="What is 2+2?", answer="4", filepath="additional_qa.csv")
from praisonaiagents.tools.train.data.generatecot import GenerateCOT# Define math problems with answersmath_problems = { "A store offers a 20% discount on a $50 item. What is the final price?": "$40", "If 3x + 7 = 22, what is x?": "5", "A triangle has sides 3, 4, and 5. Is it a right triangle?": "Yes", "What is the compound interest on $1000 at 5% for 2 years?": "$102.50", "How many ways can you arrange 4 different books on a shelf?": "24"}# Initialize generatorcot_gen = GenerateCOT( qa_pairs=math_problems, model="gpt-4o-mini", temperature=0.7, verbose=True)# Generate solutionsprint("Generating Chain-of-Thought solutions...")for question, expected_answer in math_problems.items(): # Generate solution solution = cot_gen.cot_run_dict(question) # Check correctness is_correct = cot_gen.cot_check(question, expected_answer) # If incorrect, find error and improve if not is_correct: error = cot_gen.cot_find_error(question, solution['thought_process']) improved = cot_gen.cot_improve(question, solution['thought_process']) print(f"Error found: {error}") print(f"Improved solution generated")# Export datasetcot_gen.cot_export_json_with_qa_pairs("math_cot_training.json")cot_gen.cot_export_csv_with_qa_pairs("math_cot_training.csv")# Upload to HuggingFace (optional)cot_gen.cot_upload_to_huggingface( repo_name="my-math-cot-dataset", token="your-hf-token")
# Multiple choice questionsmc_questions = { "Which planet is closest to the sun? A) Venus B) Mercury C) Earth D) Mars": "B) Mercury", "What is the chemical symbol for gold? A) Go B) Gd C) Au D) Ag": "C) Au"}# Word problemsword_problems = { "John has 5 apples. He gives 2 to Mary and buys 3 more. How many does he have now?": "6", "A train leaves at 2:00 PM traveling 60 mph. When will it reach a station 150 miles away?": "4:30 PM"}# Code-related questionscode_questions = { "What does list.append() return in Python?": "None", "What is the time complexity of binary search?": "O(log n)"}# Create specialized generators for each typemc_gen = GenerateCOT(qa_pairs=mc_questions, temperature=0.3)word_gen = GenerateCOT(qa_pairs=word_problems, temperature=0.7)code_gen = GenerateCOT(qa_pairs=code_questions, temperature=0.5)
# Generate step-by-step solutions for educational materialseducational_agent = Agent( name="Education Agent", instructions="Create detailed, educational explanations suitable for students", tools=[cot_save])# Generate explanations for various topicstopics = ["Pythagorean theorem", "Photosynthesis", "Supply and demand"]for topic in topics: # Use agent.start() to run the task result = educational_agent.start(f"Explain {topic} with clear reasoning steps") print(f"Explained: {topic}")
# Fix encoding issuescot_save( input_data="Problem with special characters: café", output_data={"answer": "résumé"}, filename="data.csv", encoding='utf-8-sig' # Use for Excel compatibility)
Large Dataset Handling
# Process large datasets in chunkschunk_size = 1000for i in range(0, len(data), chunk_size): chunk = data[i:i+chunk_size] process_chunk(chunk)
Hugging Face Upload Failures
# Retry logic for uploadsimport timemax_retries = 3for attempt in range(max_retries): try: cot_upload_to_huggingface(dataset_path, dataset_name) break except Exception as e: if attempt < max_retries - 1: time.sleep(2 ** attempt) # Exponential backoff else: raise