MasteredUltraInstinct commited on
Commit
7b2126f
·
verified ·
1 Parent(s): ec61241

Upload 2 files

Browse files
Files changed (2) hide show
  1. llm_utils.py +90 -0
  2. theorems.yaml +92 -0
llm_utils.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import yaml
3
+
4
+ # === Load theorems.yaml and render it into clean context text for LLM ===
5
+ def load_theorem_context(yaml_path="theorems.yaml"):
6
+ with open(yaml_path, 'r') as f:
7
+ data = yaml.safe_load(f)
8
+
9
+ if not isinstance(data, dict):
10
+ return "⚠️ Invalid theorems format in YAML."
11
+
12
+ context_lines = []
13
+ for idx, th in enumerate(data.get('theorems', []), 1):
14
+ context_lines.append(
15
+ f"**Theorem {idx}: {th.get('name', 'Unnamed')}**\n"
16
+ f"- **Statement**: {th.get('statement', 'N/A')}\n"
17
+ f"- **Tags**: {', '.join(th.get('tags', []))}\n"
18
+ f"- **When to Use**: {th.get('when_to_use', 'N/A')}\n"
19
+ f"- **Short Explanation**: {th.get('short_explanation', 'N/A')}\n"
20
+ )
21
+ context_lines.append('---')
22
+
23
+ return "\n".join(context_lines)
24
+
25
+ # === Build prompt using user steps and theorem context ===
26
+ def build_prompt(equation_type, solution_text, theorem_context):
27
+ return (
28
+ f"You are a helpful math tutor. Below is a theorem reference database.\n\n"
29
+ f"Each theorem includes:\n"
30
+ f"- Name\n- Statement\n- Tags\n- When to use\n- Short Explanation\n\n"
31
+ f"---\n\n"
32
+ f"### 📘 Theorem Database:\n\n"
33
+ f"{theorem_context}\n\n"
34
+ f"---\n\n"
35
+ f"### 🧮 User Steps for solving a {equation_type} equation:\n\n"
36
+ f"{solution_text}\n\n"
37
+ f"---\n\n"
38
+ f"### 🎯 Task:\n"
39
+ f"Explain each solution step clearly.\n"
40
+ f"Use relevant theorems by number or name.\n"
41
+ f"Make it understandable to a smart high school student.\n"
42
+ f"Focus on reasoning, not just restating the steps or theorems."
43
+ )
44
+
45
+ # === Request LLM explanation ===
46
+ def explain_with_llm(solution_text, equation_type, llm_url, yaml_path="theorems.yaml"):
47
+ try:
48
+ if not llm_url or not llm_url.strip().startswith("http"):
49
+ return "❌ Invalid or missing LLM URL."
50
+
51
+ theorem_context = load_theorem_context(yaml_path)
52
+ prompt = build_prompt(equation_type, solution_text, theorem_context)
53
+
54
+ response = requests.post(
55
+ f"{llm_url.strip()}/explain",
56
+ json={"prompt": prompt},
57
+ timeout=90
58
+ )
59
+
60
+ if response.status_code == 200:
61
+ result = response.json()
62
+
63
+ if isinstance(result, dict):
64
+ return result.get("explanation", "❌ No explanation returned.")
65
+ elif isinstance(result, list):
66
+ return result[0] if result else "❌ Empty response list."
67
+ else:
68
+ return f"❌ Unexpected LLM response format: {type(result)}"
69
+
70
+ return f"❌ LLM request failed: {response.status_code}"
71
+
72
+ except Exception as e:
73
+ return f"❌ LLM Error: {e}"
74
+
75
+ # === Request fallback if parsing failed ===
76
+ def request_llm_fallback(bad_input, llm_url):
77
+ try:
78
+ response = requests.post(
79
+ f"{llm_url.strip()}/clean",
80
+ json={"prompt": bad_input},
81
+ timeout=20
82
+ )
83
+ result = response.json()
84
+ if isinstance(result, dict):
85
+ return result.get("cleaned_latex", bad_input)
86
+ return bad_input
87
+ except:
88
+ return bad_input
89
+
90
+
theorems.yaml ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ theorems:
2
+ - name: Fundamental Theorem of Algebra
3
+ statement: Every non-zero polynomial of degree n with complex coefficients has exactly n complex roots, counted with multiplicity.
4
+ tags: [roots, complex, algebra]
5
+ when_to_use: When identifying the total number of complex roots of a polynomial.
6
+ short_explanation: Guarantees that a polynomial of degree n has n roots in the complex number system.
7
+
8
+ - name: Rational Root Theorem
9
+ statement: Any rational root of a polynomial with integer coefficients is a factor of the constant term divided by a factor of the leading coefficient.
10
+ tags: [rational, integer, divisibility]
11
+ when_to_use: To test possible rational roots of polynomials with integer coefficients.
12
+ short_explanation: Helps guess rational roots based on coefficients; useful before trying numerical methods.
13
+
14
+ - name: Complex Conjugate Root Theorem
15
+ statement: If a polynomial has real coefficients and a complex root a + bi, then its conjugate a - bi is also a root.
16
+ tags: [complex, conjugate, real]
17
+ when_to_use: After finding one complex root in real polynomials.
18
+ short_explanation: Ensures non-real roots appear in conjugate pairs when coefficients are real.
19
+
20
+ - name: Remainder Theorem
21
+ statement: The remainder of f(x) divided by (x - c) is f(c).
22
+ tags: [evaluation, factor, testing]
23
+ when_to_use: When checking if (x - c) is a factor of a polynomial.
24
+ short_explanation: Allows fast testing of values as roots by plugging into the polynomial.
25
+
26
+ - name: Factor Theorem
27
+ statement: (x - c) is a factor of f(x) if and only if f(c) = 0.
28
+ tags: [roots, factors]
29
+ when_to_use: After evaluating f(c) and getting 0.
30
+ short_explanation: Links remainder zero directly to factorization.
31
+
32
+ - name: Descartes’ Rule of Signs
33
+ statement: The number of positive real roots is equal to the number of sign changes or less by an even number.
34
+ tags: [signs, real, counting]
35
+ when_to_use: To estimate number of positive or negative real roots.
36
+ short_explanation: Gives an upper bound on number of real roots based on coefficient signs.
37
+
38
+ - name: Vieta’s Formulas (Quadratic Case)
39
+ statement: For ax² + bx + c = 0, sum of roots is -b/a and product is c/a.
40
+ tags: [roots, coefficients, relationships]
41
+ when_to_use: When relating roots to coefficients or vice versa.
42
+ short_explanation: Encodes root relationships algebraically, useful for reverse-engineering equations.
43
+
44
+ - name: Quadratic Formula
45
+ statement: The solutions to ax² + bx + c = 0 are given by x = [-b ± sqrt(b² - 4ac)] / (2a).
46
+ tags: [quadratic, formula, solution]
47
+ when_to_use: To directly solve any quadratic equation.
48
+ short_explanation: Universal formula for solving second-degree equations, gives real or complex roots.
49
+
50
+ - name: Cube Root of Unity Theorem
51
+ statement: The cube roots of unity are 1, ω, and ω² where ω = -1/2 + sqrt(3)/2 * i.
52
+ tags: [roots of unity, complex, cubic]
53
+ when_to_use: To factor or solve x³ + 1 = 0 or similar.
54
+ short_explanation: Provides structure for solving special cubics using symmetric roots.
55
+
56
+ - name: Unique Solution Condition (2x2 Systems)
57
+ statement: A linear system ax + by = c, dx + ey = f has a unique solution if ae - bd ≠ 0.
58
+ tags: [linear, determinant, solution condition]
59
+ when_to_use: To check if a system of two equations in two variables has a unique solution.
60
+ short_explanation: The determinant must be non-zero for a unique solution to exist.
61
+
62
+ - name: Elimination Method
63
+ statement: Linear combinations of two equations can eliminate a variable to solve the system.
64
+ tags: [linear, elimination]
65
+ when_to_use: To reduce a 2-variable system to one equation.
66
+ short_explanation: Combines equations strategically to remove variables and simplify.
67
+
68
+ - name: Substitution Method
69
+ statement: Solve one equation for a variable and substitute into the other.
70
+ tags: [substitution, linear]
71
+ when_to_use: When one variable is easy to isolate.
72
+ short_explanation: Reduces a system to a single-variable equation by replacement.
73
+
74
+ - name: Gauss Elimination (Conceptual)
75
+ statement: Any system of linear equations can be reduced using row operations to echelon form.
76
+ tags: [system, reduction, matrix]
77
+ when_to_use: For solving or analyzing larger systems or performing algorithmic solutions.
78
+ short_explanation: Encodes the algebraic elimination steps in matrix language. Useful for generalization.
79
+
80
+ - name: Imaginary Unit Identity
81
+ statement: i² = -1 defines the imaginary unit.
82
+ tags: [complex, imaginary, identity]
83
+ when_to_use: When solving quadratics with negative discriminant.
84
+ short_explanation: Enables extension of square roots to negative numbers, yielding complex solutions.
85
+
86
+ - name: Root Multiplicity
87
+ statement: If (x - c)^k divides the polynomial but (x - c)^(k+1) does not, then c is a root of multiplicity k.
88
+ tags: [multiplicity, roots, factor]
89
+ when_to_use: To analyze repeated roots.
90
+ short_explanation: Explains why some roots repeat and how they affect the shape of the graph.
91
+
92
+