Spaces:
Sleeping
Sleeping
File size: 11,183 Bytes
8e8700f ed4cfc0 8e8700f ed4cfc0 28999aa 8e8700f 28999aa 8e8700f ed4cfc0 2730094 ed4cfc0 8e8700f ed4cfc0 8e8700f ed4cfc0 8e8700f ed4cfc0 b86678a ed4cfc0 22ff90b f65b71f 8e8700f ed4cfc0 8e8700f f4a75f1 28999aa 2730094 28999aa f4a75f1 28999aa f4a75f1 28999aa f4a75f1 d0322c1 28999aa f4a75f1 28999aa f4a75f1 ed4cfc0 2730094 28999aa 2730094 8e8700f 8f95c54 8e8700f 8f95c54 8e8700f 2730094 8e8700f 2730094 8e8700f 2730094 8e8700f 8f95c54 2730094 ed4cfc0 8e8700f ed4cfc0 8e8700f ed4cfc0 8e8700f ed4cfc0 89c4461 8e8700f d249a48 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | import openai
from sentence_transformers import SentenceTransformer, util
import gradio as gr
import os
from openai import OpenAI
client = OpenAI(api_key=os.getenv('openai')) # Replace with your actual API key
# Initialize LLM (e.g., GPT-3 or GPT-4)
#openai.api_key = os.getenv('openai')
# Theorem database (store theorems and their rules)
theorems = [
{
"name": "Pythagorean Theorem",
"description": (
"In a right triangle, the square of the hypotenuse is equal to the "
"sum of the squares of the other two sides. Commonly used to find "
"the length of a side when two sides are known."
),
"keywords": ["triangle", "hypotenuse", "right triangle", "geometry", "distance"],
"formula": "c**2 = a**2 + b**2",
},
{
"name": "Quadratic Formula",
"description": (
"Used to find the roots of a quadratic equation in the form ax^2 + bx + c = 0. "
"It works by substituting coefficients into the formula."
),
"keywords": ["quadratic", "roots", "equation", "solve", "polynomial"],
"formula": "x = (-b ± sqrt(b**2 - 4*a*c)) / (2*a)",
},
{
"name": "Area of a Circle",
"description": (
"To calculate the area of a circle given its radius. This theorem "
"is fundamental in geometry."
),
"keywords": ["circle", "area", "geometry", "radius", "π"],
"formula": "A = π * r**2",
},
{
"name": "Law of Sines",
"description": (
"In any triangle, the ratios of the lengths of a side to the sine of "
"its opposite angle are equal."
),
"keywords": ["triangle", "sine", "angles", "geometry", "ratios"],
"formula": "a/sin(A) = b/sin(B) = c/sin(C)",
},
{
"name": "Law of Cosines",
"description": (
"Relates the lengths of the sides of a triangle to the cosine of one "
"of its angles. Used when the triangle is not a right triangle."
),
"keywords": ["triangle", "cosine", "angles", "geometry", "distance"],
"formula": "c**2 = a**2 + b**2 - 2*a*b*cos(C)",
},
{
"name": "Heron's Formula",
"description": (
"Used to calculate the area of a triangle when the lengths of all three "
"sides are known."
),
"keywords": ["triangle", "area", "geometry", "sides", "semi-perimeter"],
"formula": "A = sqrt(s*(s-a)*(s-b)*(s-c)) where s = (a+b+c)/2",
},
{
"name": "Binomial Theorem",
"description": (
"Provides a formula for expanding expressions raised to a power, "
"such as (x + y)^n."
),
"keywords": ["binomial", "expansion", "algebra", "power", "polynomial"],
"formula": "(x + y)^n = Σ[k=0 to n] (nCk * x^(n-k) * y^k)",
},
{
"name": "Fundamental Theorem of Calculus",
"description": (
"Links the concept of differentiation and integration. It states that the "
"definite integral of a function can be computed using its antiderivative."
),
"keywords": ["calculus", "integral", "derivative", "antiderivative", "area"],
"formula": "∫[a to b] f(x) dx = F(b) - F(a), where F'(x) = f(x)",
},
{
"name": "Differentiation Rules",
"description": (
"Rules for finding the derivative of various types of functions, "
"including power, product, quotient, and chain rules."
),
"keywords": ["derivative", "rules", "differentiation", "calculus", "slope"],
"formula": [
"d/dx [x^n] = n*x^(n-1)",
"d/dx [u*v] = u'v + uv'",
"d/dx [u/v] = (u'v - uv')/v^2",
],
},
{
"name": "Integration by Parts",
"description": (
"A technique for evaluating integrals, derived from the product rule of differentiation."
),
"keywords": ["integration", "parts", "calculus", "product", "antiderivative"],
"formula": "∫u dv = uv - ∫v du",
},
{
"name": "Mean Value Theorem",
"description": (
"States that for a continuous and differentiable function, there exists at least one point "
"where the derivative equals the average slope over an interval."
),
"keywords": ["calculus", "slope", "average", "differentiation", "continuous"],
"formula": "f'(c) = (f(b) - f(a)) / (b - a) for some c in (a, b)",
},
{
"name": "Commutative Property of Addition",
"description": (
"In arithmetic and algebra, changing the order of addends does not change the sum."
),
"keywords": ["addition", "commutative", "arithmetic", "algebra"],
"formula": "a + b = b + a",
},
{
"name": "Commutative Property of Multiplication",
"description": (
"In arithmetic and algebra, changing the order of factors does not change the product."
),
"keywords": ["multiplication", "commutative", "arithmetic", "algebra"],
"formula": "a * b = b * a",
},
{
"name": "Associative Property of Addition",
"description": (
"The grouping of addends does not affect the sum."
),
"keywords": ["addition", "associative", "arithmetic", "algebra"],
"formula": "(a + b) + c = a + (b + c)",
},
{
"name": "Associative Property of Multiplication",
"description": (
"The grouping of factors does not affect the product."
),
"keywords": ["multiplication", "associative", "arithmetic", "algebra"],
"formula": "(a * b) * c = a * (b * c)",
},
]
# Initialize semantic model
model = SentenceTransformer('paraphrase-MiniLM-L6-v2')
# Function to find the closest relevant theorems (multiple theorems possible)
def find_relevant_theorems(query):
query_embedding = model.encode(query, convert_to_tensor=True)
relevant_theorems = []
for theorem in theorems:
concatenated_string = (
f"Name: {theorem['name']}\n"
f"Description: {theorem['description']}\n"
f"Keywords: {', '.join(theorem['keywords'])}\n"
f"Formula: {theorem['formula']}"
)
theorem_embedding = model.encode(concatenated_string, convert_to_tensor=True)
similarity = util.pytorch_cos_sim(query_embedding, theorem_embedding).item()
print(f"Similarity with {theorem['name']}: {similarity}") # Debugging
if similarity > 0.35: # A threshold to consider multiple relevant theorems
relevant_theorems.append((theorem, similarity))
# Sort the theorems by similarity
relevant_theorems.sort(key=lambda x: x[1], reverse=True)
return relevant_theorems
# Function to generate the solution using GPT
def solve_problem_with_gpt(query, theorems_used):
# Create a prompt for GPT to solve the problem
prompt = f"Using one or some of the following theorems: {theorems_used}, solve the problem: {query}."
try:
# Use the updated API structure
response = client.chat.completions.create(
model="gpt-4", # Or use another model like "gpt-3.5-turbo"
messages=[
{"role": "system", "content": "You are a mathematical assistant that solves problems using provided theorems."},
{"role": "user", "content": prompt}
],
)
result = response.choices[0].message.content
return result # Return the solution
except Exception as e:
return f"Error: {str(e)}" # Return error message
def validate_solution_with_gpt(solution, query, relevant_theorems):
"""
Validate the solution using GPT by asking if the solution is consistent with the given theorems.
"""
theorems_summary = "\n".join(
[f"{th['name']}: {th['description']}\nFormula: {th['formula']}" for th in relevant_theorems]
)
validation_prompt = f"""
You are an expert validator for mathematical solutions.
User Query: {query}
Solution Provided:
{solution}
Relevant Theorems:
{theorems_summary}
Is the solution consistent with the relevant theorems? If not, explain why.
"""
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are an expert validator for mathematical problems."},
{"role": "user", "content": validation_prompt}
]
)
feedback = response.choices[0].message.content
return "Yes" in feedback, feedback
# Main agent function to handle the query
def agent(query):
loop=0
while True:
loop+=1
# Step 1: Find the closest relevant theorems
relevant_theorems = find_relevant_theorems(query)
if not relevant_theorems:
return "No relevant theorem found."
# Step 2: Solve the problem using GPT and the relevant theorems
theorems_used = [theorem[0] for theorem in relevant_theorems] # Get theorems with the highest similarity
result = solve_problem_with_gpt(query, theorems_used)
# Step 3: Validate the solution using GPT
#is_valid, validation_feedback = validate_solution_with_gpt(result, query, theorems_used)
is_valid, feedback = validate_solution_with_gpt(result, query, theorems_used)
if is_valid:
return f"Solution: {result}\nValidation Feedback: The solution is valid."
else:
print(f"Validation feedback: {feedback}\nRestarting the process...\n")
if loop<3:
continue
else:
return f"Solution does not look valid\nValidation Feedback: {feedback}"
# Optionally, you could loop back here if desired
# Gradio Interface
def gradio_interface(query):
return agent(query)
# Create the Gradio interface
iface = gr.Interface(
fn=gradio_interface,
inputs="text",
outputs="text",
title="Math Theorem Agent",
description="Ask any math-related question, and the agent will use relevant theorems to solve it and validate the solution."
)
examples = [
"What is the area of a circle with radius 5?",
"What is the integral of 2x from 0 to 5?",
"Find the hypotenuse of a right triangle with sides 3 and 4.",
"Calculate the derivative of x^3.",
"Expand the expression (x + y)^3.",
"Is a+b=b+a always true?",
"Does 3*(4*5) equal (3*4)*5?",
"Check if the triangle with sides 5, 12, and 13 is a right triangle.",
"How can the relationship between integration and differentiation simplify solving problems?",
"Which theorems can be used to solve problems about the area of triangles?"
]
# Gradio Interface
iface = gr.Interface(
fn=gradio_interface,
inputs="text",
outputs="text",
title="Math Theorem Agent",
description="Ask any math-related question, and the agent will use relevant theorems to solve it and validate the solution.",
examples=examples # Add examples here
)
# Launch the interface
iface.launch()
|