Spaces:
Sleeping
Sleeping
Download app.py from quenti/logic-math: direct link, hf CLI and curl.
- Browser
- Download file 11.2 kB
-
https://huggingface.co/spaces/quenti/logic-math/resolve/main/app.py
- Command line
-
hf download hf://spaces/quenti/logic-math/app.py
-
curl -L -o app.py https://huggingface.co/spaces/quenti/logic-math/resolve/main/app.py
11.2 kB
| 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() | |