File size: 3,645 Bytes
129f783
 
 
 
235d29a
129f783
 
ac314a8
 
129f783
235d29a
fb60f37
129f783
235d29a
129f783
 
 
8f392ee
235d29a
 
 
 
 
 
 
 
2463eb2
 
 
235d29a
 
2463eb2
 
 
235d29a
129f783
 
 
235d29a
 
129f783
 
 
 
 
 
235d29a
129f783
 
 
 
 
b3823bf
235d29a
 
 
 
 
129f783
 
 
4777809
129f783
 
 
 
 
 
 
 
 
235d29a
129f783
 
 
 
 
 
 
235d29a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129f783
 
235d29a
129f783
 
 
6e4e8cb
235d29a
b3823bf
235d29a
 
4777809
129f783
 
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
import os
import re
import json
import requests
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

# Secure Claude API Key (use Hugging Face Secrets for production)
CLAUDE_API_KEY = os.environ["CLAUDE_API_KEY"]

# Extract final answer (including LaTeX $...$ or $$...$$)
def extract_final_answer(text):
    if not text:
        return None

    # βœ… Match full final answer line first (for things like: Final Answer: $x = 3$ or $x = 2$)
    match_full = re.search(r'final answer[:\-]?\s*(.*)', text, re.IGNORECASE)
    if match_full:
        answer = match_full.group(1).strip()
        if answer: return answer

    # βœ… Match LaTeX-style $$...$$ if used alone
    match_dollars = re.search(r'\$\$(.+?)\$\$', text)
    if match_dollars:
        return match_dollars.group(1).strip()

    # βœ… Match LaTeX-style $...$ if used alone
    match_dollar = re.search(r'\$(.+?)\$', text)
    if match_dollar:
        return match_dollar.group(1).strip()

    # βœ… Final fallback: return last number
    fallback = re.findall(r'\b\d+\.?\d*\b', text)
    return fallback[-1].strip() if fallback else None


# Claude API call function
def call_claude(prompt):
    headers = {
        "x-api-key": CLAUDE_API_KEY,
        "Content-Type": "application/json",
        "anthropic-version": "2023-06-01"
    }

    body = {
        "model": "claude-3-opus-20240229",
        "max_tokens": 1024,
        "temperature": 0.5,
        "system": (
            "You are a helpful and clear Year 5–10 maths tutor. "
            "Provide accurate, step-by-step explanations in about 5–8 natural language steps. "
            "Avoid calculator-style breakdowns or repeated dashes. "
            "Use natural teacher-style explanations. "
            "Use LaTeX formatting for mathematical expressions inside $...$ or $$...$$. "
            "At the end, clearly write: Final Answer: $[answer]$"
        ),
        "messages": [{"role": "user", "content": prompt}]
    }

    try:
        res = requests.post("https://api.anthropic.com/v1/messages", headers=headers, data=json.dumps(body), timeout=20)
        if res.status_code == 200:
            return res.json()["content"][0]["text"]
        else:
            return f"❌ Claude API Error {res.status_code}: {res.text}"
    except Exception as e:
        return f"❌ Claude API call failed: {e}"

# Solve route
@app.route("/solve", methods=["POST"])
def solve():
    data = request.get_json()
    question = data.get("question", "")
    if not question.strip():
        return jsonify({"error": "No question provided."}), 400

    first_response = call_claude(question)
    final_answer = extract_final_answer(first_response)

    # Retry with clearer instruction if the answer wasn't found
    if not final_answer:
        retry_prompt = (
            f"Your previous answer was unclear.\n\n"
            f"❓ Question: {question}\n"
            f"❌ Response: {first_response}\n"
            f"Please retry with clear steps and end with: Final Answer: $[answer]$"
        )
        retry_response = call_claude(retry_prompt)
        retry_answer = extract_final_answer(retry_response)
        return jsonify({
            "steps": retry_response,
            "final_answer": retry_answer or "Not found"
        })

    return jsonify({
        "steps": first_response,
        "final_answer": final_answer
    })


# Serve frontend HTML for local/browser view
@app.route("/", methods=["GET"])
def serve_index():
    return send_from_directory(".", "index.html")

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)