Enable AI models to think step-by-step, reason logically, and solve complex problems
import requests
class ReasoningAssistant:
def __init__(self, api_key):
self.api_key = api_key
def chain_of_thought(self, problem, model="gpt-4o"):
"""Apply chain of thought reasoning to solve a problem"""
system_prompt = """You are an expert problem solver. When given a problem:
1. First, clearly understand what is being asked
2. Break the problem down into logical steps
3. Work through each step methodically
4. Show your reasoning at each stage
5. Double-check your work
6. Provide a clear final answer
Think step by step and show your work."""
user_prompt = f"""Let's think step by step about this problem:
{problem}
Please work through this systematically, showing each step of your reasoning."""
response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
],
"temperature": 0.3 # Lower temperature for more focused reasoning
}
)
return response.json()["choices"][0]["message"]["content"]
def verify_reasoning(self, problem, solution, model="gpt-4o"):
"""Verify the reasoning in a solution"""
verification_prompt = f"""Please verify this reasoning:
Original Problem:
{problem}
Proposed Solution:
{solution}
Check:
1. Are all steps logically sound?
2. Are there any errors in calculation or logic?
3. Is the final answer correct?
4. Are there alternative approaches?
5. What assumptions were made?
Provide a detailed verification analysis."""
response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [
{
"role": "system",
"content": "You are a logical reasoning validator. Carefully check reasoning for errors and provide constructive feedback."
},
{"role": "user", "content": verification_prompt}
],
"temperature": 0.2
}
)
return response.json()["choices"][0]["message"]["content"]
def solve_with_multiple_approaches(self, problem, model="gpt-4o"):
"""Solve a problem using multiple reasoning approaches"""
approaches = [
"analytical approach (break into mathematical steps)",
"logical deduction approach (apply rules systematically)",
"creative problem-solving approach (think outside the box)",
"systematic elimination approach (rule out possibilities)"
]
solutions = []
for approach in approaches:
prompt = f"""Solve this problem using a {approach}:
Problem: {problem}
Use the specified approach and explain your reasoning clearly."""
response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [
{
"role": "system",
"content": f"You are solving problems using a {approach}. Apply this method systematically."
},
{"role": "user", "content": prompt}
],
"temperature": 0.4
}
)
solution = response.json()["choices"][0]["message"]["content"]
solutions.append({
"approach": approach,
"solution": solution
})
# Compare and synthesize solutions
synthesis_prompt = f"""Compare these different solutions to the same problem:
Problem: {problem}
Solutions:
{chr(10).join([f"{i+1}. {sol['approach'].title()}:{chr(10)}{sol['solution']}{chr(10)}" for i, sol in enumerate(solutions)])}
Analyze:
1. Which solution is most accurate?
2. What are the strengths/weaknesses of each approach?
3. Can you synthesize the best elements into an optimal solution?
4. Are there any contradictions that need to be resolved?
Provide a final, best solution with clear reasoning."""
synthesis_response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [
{
"role": "system",
"content": "You are an expert at comparing and synthesizing different problem-solving approaches."
},
{"role": "user", "content": synthesis_prompt}
],
"temperature": 0.3
}
)
return {
"individual_solutions": solutions,
"synthesis": synthesis_response.json()["choices"][0]["message"]["content"]
}
# Usage examples
reasoning_assistant = ReasoningAssistant("YOUR_API_KEY")
# Chain of thought reasoning
problem = """A train travels 120 miles in the first 2 hours, then 180 miles in the next 3 hours.
If it needs to maintain an average speed of 65 mph for the entire journey of 8 hours,
how fast must it travel in the remaining 3 hours?"""
solution = reasoning_assistant.chain_of_thought(problem)
print("Chain of Thought Solution:")
print(solution)
# Verify the reasoning
verification = reasoning_assistant.verify_reasoning(problem, solution)
print("\nVerification:")
print(verification)
# Multiple approaches
multi_solutions = reasoning_assistant.solve_with_multiple_approaches(
"In a group of 30 people, 18 speak English, 15 speak Spanish, and 8 speak both languages. How many people speak neither language?"
)
print("\nMultiple Approaches:")
print(multi_solutions["synthesis"])
class SocraticReasoning:
def __init__(self, api_key):
self.api_key = api_key
self.conversation_history = []
def socratic_dialogue(self, initial_question, model="gpt-4o"):
"""Engage in Socratic questioning to explore a topic deeply"""
system_prompt = """You are a Socratic tutor. Your role is to guide learning through
thoughtful questions rather than direct answers.
- Ask probing questions that lead to deeper understanding
- Challenge assumptions gently
- Help the student discover answers through their own reasoning
- Build on previous responses to go deeper
- Only provide direct answers when the student has fully explored the topic
Use the Socratic method effectively."""
self.conversation_history = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": f"I want to understand: {initial_question}"}
]
return self._get_response(model)
def respond(self, student_response, model="gpt-4o"):
"""Continue the Socratic dialogue"""
self.conversation_history.append({
"role": "user",
"content": student_response
})
return self._get_response(model)
def _get_response(self, model):
"""Get AI response maintaining conversation context"""
response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": self.conversation_history,
"temperature": 0.7
}
)
ai_response = response.json()["choices"][0]["message"]["content"]
self.conversation_history.append({
"role": "assistant",
"content": ai_response
})
return ai_response
# Usage
socratic = SocraticReasoning("YOUR_API_KEY")
# Start Socratic dialogue
response = socratic.socratic_dialogue("Why do objects fall down instead of up?")
print("Tutor:", response)
# Continue dialogue
response = socratic.respond("Because gravity pulls them down.")
print("Tutor:", response)
response = socratic.respond("Gravity is a force that attracts objects to Earth.")
print("Tutor:", response)
class DialecticalReasoning:
def __init__(self, api_key):
self.api_key = api_key
def dialectical_analysis(self, topic, model="gpt-4o"):
"""Analyze a topic using dialectical reasoning (thesis, antithesis, synthesis)"""
# Step 1: Establish thesis
thesis_prompt = f"""Present a strong argument FOR this position: {topic}
Provide:
1. The main thesis statement
2. Key supporting arguments
3. Evidence and examples
4. Logical reasoning
Make the strongest possible case for this position."""
thesis_response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [
{
"role": "system",
"content": "You are arguing FOR the given position. Present the strongest possible case."
},
{"role": "user", "content": thesis_prompt}
],
"temperature": 0.4
}
)
thesis = thesis_response.json()["choices"][0]["message"]["content"]
# Step 2: Establish antithesis
antithesis_prompt = f"""Now present a strong argument AGAINST this position: {topic}
Consider the thesis that was just presented:
{thesis}
Provide:
1. Counter-arguments to the thesis
2. Alternative perspectives
3. Weaknesses in the original reasoning
4. Contradictory evidence
Make the strongest possible case against the position."""
antithesis_response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [
{
"role": "system",
"content": "You are arguing AGAINST the given position. Present the strongest possible counter-case."
},
{"role": "user", "content": antithesis_prompt}
],
"temperature": 0.4
}
)
antithesis = antithesis_response.json()["choices"][0]["message"]["content"]
# Step 3: Synthesis
synthesis_prompt = f"""Now synthesize these opposing viewpoints into a higher understanding:
Topic: {topic}
THESIS (Arguments FOR):
{thesis}
ANTITHESIS (Arguments AGAINST):
{antithesis}
Create a SYNTHESIS that:
1. Acknowledges valid points from both sides
2. Resolves contradictions where possible
3. Identifies areas of common ground
4. Proposes a more nuanced understanding
5. Suggests practical implications
Aim for a balanced, sophisticated perspective that transcends the original debate."""
synthesis_response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [
{
"role": "system",
"content": "You are synthesizing opposing viewpoints into a higher understanding. Be balanced and nuanced."
},
{"role": "user", "content": synthesis_prompt}
],
"temperature": 0.5
}
)
synthesis = synthesis_response.json()["choices"][0]["message"]["content"]
return {
"topic": topic,
"thesis": thesis,
"antithesis": antithesis,
"synthesis": synthesis
}
# Usage
dialectical = DialecticalReasoning("YOUR_API_KEY")
analysis = dialectical.dialectical_analysis(
"Artificial Intelligence will have a net positive impact on society"
)
print("THESIS:")
print(analysis["thesis"])
print("\nANTITHESIS:")
print(analysis["antithesis"])
print("\nSYNTHESIS:")
print(analysis["synthesis"])
class CausalReasoning:
def __init__(self, api_key):
self.api_key = api_key
def analyze_causation(self, phenomenon, model="gpt-4o"):
"""Analyze the causal relationships in a phenomenon"""
prompt = f"""Analyze the causal relationships involved in: {phenomenon}
Provide a comprehensive causal analysis including:
1. IMMEDIATE CAUSES (direct triggers)
2. ROOT CAUSES (underlying factors)
3. CONTRIBUTING FACTORS (things that make it more likely)
4. NECESSARY CONDITIONS (things that must be present)
5. SUFFICIENT CONDITIONS (things that guarantee the outcome)
6. CAUSAL CHAIN (sequence of cause and effect)
7. FEEDBACK LOOPS (how effects influence causes)
8. COUNTERFACTUALS (what would happen if causes were absent)
Use clear logical reasoning and consider multiple levels of causation."""
response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [
{
"role": "system",
"content": "You are an expert in causal analysis. Think systematically about cause-and-effect relationships."
},
{"role": "user", "content": prompt}
],
"temperature": 0.3
}
)
return response.json()["choices"][0]["message"]["content"]
def evaluate_causal_claim(self, claim, model="gpt-4o"):
"""Evaluate the validity of a causal claim"""
prompt = f"""Evaluate this causal claim: "{claim}"
Assess:
1. LOGICAL VALIDITY: Is the causal logic sound?
2. TEMPORAL SEQUENCE: Does the cause precede the effect?
3. CORRELATION vs CAUSATION: Is there evidence of actual causation?
4. ALTERNATIVE EXPLANATIONS: What other causes might explain the effect?
5. CONFOUNDING VARIABLES: What other factors might be involved?
6. STRENGTH OF EVIDENCE: How strong is the causal evidence?
7. SCOPE OF CLAIM: Under what conditions does this causation hold?
8. PRACTICAL IMPLICATIONS: What does this mean for prediction/control?
Provide a thorough critical evaluation."""
response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [
{
"role": "system",
"content": "You are a critical thinker evaluating causal claims. Be rigorous and look for potential flaws."
},
{"role": "user", "content": prompt}
],
"temperature": 0.3
}
)
return response.json()["choices"][0]["message"]["content"]
# Usage
causal = CausalReasoning("YOUR_API_KEY")
# Analyze causation
analysis = causal.analyze_causation("The rise in global temperatures over the past century")
print("Causal Analysis:")
print(analysis)
# Evaluate causal claim
evaluation = causal.evaluate_causal_claim(
"Social media use causes depression in teenagers"
)
print("\nCausal Claim Evaluation:")
print(evaluation)
class TRIZReasoning:
def __init__(self, api_key):
self.api_key = api_key
def solve_with_triz(self, problem, model="gpt-4o"):
"""Apply TRIZ methodology to solve inventive problems"""
prompt = f"""Apply TRIZ (Theory of Inventive Problem Solving) to this problem:
Problem: {problem}
Follow the TRIZ process:
1. PROBLEM FORMULATION:
- Define the contradiction
- Identify the system and its purpose
- Determine what is preventing the ideal solution
2. CONTRADICTION ANALYSIS:
- What needs to be improved?
- What gets worse when we try to improve it?
- Technical contradiction or physical contradiction?
3. APPLY TRIZ PRINCIPLES:
- Which of the 40 inventive principles apply?
- Suggest specific applications
- Consider separation principles for physical contradictions
4. SOLUTION CONCEPTS:
- Generate multiple solution concepts
- Evaluate each against TRIZ patterns
- Identify the most promising approaches
5. IMPLEMENTATION:
- How can these concepts be realized?
- What resources are available?
- Potential obstacles and solutions
Think systematically using TRIZ methodology."""
response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [
{
"role": "system",
"content": "You are a TRIZ expert applying systematic inventive thinking to solve technical problems."
},
{"role": "user", "content": prompt}
],
"temperature": 0.4
}
)
return response.json()["choices"][0]["message"]["content"]
# Usage
triz = TRIZReasoning("YOUR_API_KEY")
solution = triz.solve_with_triz(
"Design a packaging system that keeps fragile items safe during shipping while being environmentally friendly and cost-effective"
)
print("TRIZ Solution:")
print(solution)
class SystemsThinking:
def __init__(self, api_key):
self.api_key = api_key
def systems_analysis(self, system_description, model="gpt-4o"):
"""Analyze a system using systems thinking principles"""
prompt = f"""Analyze this system using systems thinking: {system_description}
Provide a comprehensive systems analysis:
1. SYSTEM COMPONENTS:
- Key elements and subsystems
- Stakeholders and actors
- Resources and inputs
2. RELATIONSHIPS & INTERACTIONS:
- How components connect
- Information flows
- Energy/resource flows
- Dependencies
3. SYSTEM BEHAVIOR:
- Emergent properties
- System-level behaviors
- Patterns over time
4. FEEDBACK LOOPS:
- Reinforcing loops (positive feedback)
- Balancing loops (negative feedback)
- Delays in the system
5. SYSTEM STRUCTURE:
- Hierarchies and levels
- Boundaries and environment
- Purpose and function
6. LEVERAGE POINTS:
- Where small changes can have big impact
- Intervention opportunities
- Systemic solutions
7. MENTAL MODELS:
- Assumptions and beliefs
- Different perspectives
- Paradigms affecting the system
Think holistically about the system."""
response = requests.post(
"https://api.anyapi.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
},
json={
"model": model,
"messages": [
{
"role": "system",
"content": "You are a systems thinking expert. Analyze systems holistically, focusing on relationships and emergent properties."
},
{"role": "user", "content": prompt}
],
"temperature": 0.4
}
)
return response.json()["choices"][0]["message"]["content"]
# Usage
systems = SystemsThinking("YOUR_API_KEY")
analysis = systems.systems_analysis(
"The healthcare system in a large metropolitan area, including hospitals, clinics, insurance companies, patients, and government regulations"
)
print("Systems Analysis:")
print(analysis)
Reasoning Task | Recommended Model | Reasoning |
---|---|---|
Mathematical Reasoning | GPT-4o, Claude 3.5 Sonnet | Strong analytical capabilities |
Logical Deduction | Claude 3.5 Sonnet | Excellent at structured reasoning |
Creative Problem Solving | GPT-4o | Good at generating novel approaches |
Critical Analysis | Claude 3.5 Sonnet | Strong analytical and critical thinking |
Scientific Reasoning | GPT-4o, Claude 3.5 Sonnet | Good with empirical reasoning |
Philosophical Analysis | Claude 3.5 Sonnet | Strong with abstract concepts |