File size: 2,042 Bytes
1ba1ba2 | 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 | import os
import requests
API_KEY = os.getenv("API_KEY_GEMINI")
GEMINI_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={API_KEY}"
def filter_math_query(query):
"""Checks if the query is related to a mathematical topic and corrects spelling mistakes using a single API call."""
if not API_KEY:
return "⚠️ Error: Missing API key. Please configure API_KEY_GEMINI.", None
headers = {"Content-Type": "application/json"}
prompt = (
f"Analyze the following query and perform two tasks:\n"
f"1️⃣ Check whether it strictly relates to mathematics.\n"
f" - Reply only with 'MATH' if it's a valid math-related topic.\n"
f" - Reply with 'NON MATH' if it's not a mathematical subject.\n"
f"2️⃣ If the query is mathematical, correct any spelling mistakes.\n"
f" - Respond in the format 'MATH\nCorrection: [Corrected query]'.\n"
f" - If the query is not mathematical, do not provide a correction.\n\n"
f"Query: {query}"
)
data = {
"contents": [
{
"parts": [
{"text": prompt}
]
}
]
}
try:
response = requests.post(GEMINI_URL, headers=headers, json=data)
response_json = response.json()
result = response_json["candidates"][0]["content"]["parts"][0]["text"].strip()
if result.startswith("MATH"):
corrected_query = query # Default to the original query
if "Correction:" in result:
corrected_query = result.split("Correction:")[1].strip()
return "✅ Query accepted as mathematical.", corrected_query
elif "NON MATH" in result:
return "❌ Query rejected. This is not a mathematical topic.", None
else:
return f"⚠️ Error: Unexpected response from Gemini ({result})", None
except Exception as e:
return f"⚠️ Gemini API Error: {e}", None
|