Building an AI Math Solver & Explainer with Streamlit and FastAPI
- Mohammed Juyel Haque
- 5 days ago
- 2 min read
In this tutorial, we’ll walk through creating an AI-powered Math Solver & Explainer using OpenAI’s GPT model, a FastAPI backend, and a Streamlit frontend with LaTeX rendering support. Users can input math problems like "Solve 2x + 3 = 7" and receive step-by-step solutions beautifully rendered using LaTeX.

Technologies Used
FastAPI – To handle backend requests
Streamlit – For a clean, interactive UI
OpenAI API – To generate step-by-step solutions
LaTeX (via Streamlit) – For rendering mathematical expressions
Directory Structure
maths/
├── backend/
│ ├── main.py
│ └── requirements.txt
├── frontend/
│ ├── app.py
│ └── requirements.txt
└── .env
Backend Setup (FastAPI)
backend/main.api
from fastapi import FastAPI, Request
from pydantic import BaseModel
import openai
import os
from fastapi.middleware.cors import CORSMiddleware
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
class MathProblem(BaseModel):
question: str
@app.post("/solve")
async def solve_math(problem: MathProblem):
prompt = f"Solve and explain step-by-step with LaTeX math formatting: {problem.question}"
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "user", "content": prompt}
]
)
answer = response['choices'][0]['message']['content']
return {"solution": answer}
backend/requirements.txt
fastapi
uvicorn
openai
python-dotenv
Frontend Setup (Streamlit)
frontend/app.py
import streamlit as st
import requests
st.set_page_config(page_title="📐 AI Math Solver & Explainer")
st.title("📐 AI Math Solver & Explainer")
st.write("Enter a math problem (e.g., `Solve 2x + 3 = 7`)")
question = st.text_input("Your Question", placeholder="e.g., Solve 2x + 3 = 7")
if st.button("Solve"):
if not question.strip():
st.warning("Please enter a math problem.")
else:
with st.spinner("Solving..."):
try:
response = requests.post(
"http://localhost:8000/solve",
json={"question": question}
)
if response.status_code == 200:
solution = response.json()["solution"]
st.markdown("### 📘 Solution & Explanation:")
for line in solution.split("\n"):
line = line.strip()
if line.startswith("$$") and line.endswith("$$"):
st.latex(line.strip("$$"))
elif line.startswith("\\[") and line.endswith("\\]"):
st.latex(line[2:-2])
else:
st.markdown(line)
else:
st.error("Failed to get response from backend.")
except Exception as e:
st.error(f"Error: {e}")
frontend/requirements.txt
streamlit
requests
Environment Variables
Create a .env file in your project root:
OPENAI_API_KEY=" "
Run Project
Start Backend
cd backend
pip install -r requirements.txt
unicorn main:app --reload
Start Frontend
cd frontend
pip install -r requirements.txt
streamlit run app.py
Conclusion
With just a few components, I’ve built a fully functional AI-powered math tutor.
Comments