Alphin Jain commited on
Commit
0a7d2c2
ยท
0 Parent(s):

Initial commit: Math Problem Solver application

Browse files
Files changed (4) hide show
  1. .gitignore +44 -0
  2. app.py +248 -0
  3. readme.md +90 -0
  4. requirements.txt +16 -0
.gitignore ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Environment variables
2
+ .env
3
+ .env.local
4
+
5
+ # Virtual Environment
6
+ venv/
7
+ env/
8
+ ENV/
9
+
10
+ # Python cache files
11
+ __pycache__/
12
+ *.py[cod]
13
+ *$py.class
14
+ *.so
15
+ .Python
16
+ build/
17
+ develop-eggs/
18
+ dist/
19
+ downloads/
20
+ eggs/
21
+ .eggs/
22
+ lib/
23
+ lib64/
24
+ parts/
25
+ sdist/
26
+ var/
27
+ wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+
32
+ # Streamlit specific
33
+ .streamlit/secrets.toml
34
+
35
+ # Logs
36
+ *.log
37
+ logs/
38
+
39
+ # IDE specific files
40
+ .idea/
41
+ .vscode/
42
+ *.swp
43
+ *.swo
44
+ .DS_Store
app.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Math Problem Solver
2
+ # A Streamlit application that solves math problems and searches for information using Google Gemma 2 model through Groq API
3
+
4
+ import streamlit as st
5
+ import os
6
+ from langchain_groq import ChatGroq
7
+ from langchain.agents import Tool, initialize_agent
8
+ from langchain.agents.agent_types import AgentType
9
+ from langchain.prompts import PromptTemplate
10
+ from langchain_community.utilities import WikipediaAPIWrapper, ArxivAPIWrapper, DuckDuckGoSearchRun
11
+ from langchain_community.tools import WikipediaQueryRun, ArxivQueryRun
12
+ from langchain.callbacks import StreamlitCallbackHandler
13
+ from langchain.chains import LLMMathChain, LLMChain
14
+ from langchain.schema import SystemMessage
15
+ from dotenv import load_dotenv
16
+
17
+ # Load environment variables from .env file
18
+ load_dotenv()
19
+
20
+ # Page configuration
21
+ st.set_page_config(
22
+ page_title="Math Problem Solver",
23
+ page_icon="๐Ÿงฎ",
24
+ layout="wide"
25
+ )
26
+
27
+ # App title and description
28
+ st.title("๐Ÿงฎ Math Problem Solver")
29
+ st.markdown("""
30
+ This application solves mathematical problems and provides step-by-step explanations using Groq's AI models.
31
+ It can handle various math topics including:
32
+ - Arithmetic calculations
33
+ - Algebra
34
+ - Geometry
35
+ - Statistics
36
+ - Word problems
37
+ - And more!
38
+ """)
39
+
40
+ # Sidebar configuration
41
+ st.sidebar.title("โš™๏ธ Configuration")
42
+ st.sidebar.markdown("---")
43
+
44
+ # API key input - use environment variable if available
45
+ default_api_key = os.getenv("GROQ_API_KEY", "")
46
+ groq_api_key = st.sidebar.text_input(
47
+ label="Groq API Key",
48
+ value=default_api_key,
49
+ type="password",
50
+ help="Get your API key from https://console.groq.com/keys"
51
+ )
52
+
53
+ # Model selection
54
+ model_options = {
55
+ "gemma2-9b-it": "Gemma 2 9B (Fast)",
56
+ "llama3-8b-8192": "Llama 3 8B (Balanced)",
57
+ "llama3-70b-8192": "Llama 3 70B (Powerful)",
58
+ "mixtral-8x7b-32768": "Mixtral 8x7B (Comprehensive)"
59
+ }
60
+ selected_model = st.sidebar.selectbox(
61
+ "Select AI model:",
62
+ list(model_options.keys()),
63
+ format_func=lambda x: model_options[x],
64
+ index=0
65
+ )
66
+
67
+ # Advanced options
68
+ with st.sidebar.expander("Advanced Options"):
69
+ temperature = st.slider("Temperature", min_value=0.0, max_value=1.0, value=0.2, step=0.1,
70
+ help="Lower values make responses more deterministic, higher values more creative")
71
+ show_reasoning = st.checkbox("Show AI reasoning steps", value=True,
72
+ help="Display the AI's step-by-step reasoning process")
73
+
74
+ # Initialize LLM if API key is provided
75
+ if not groq_api_key:
76
+ st.info("Please add your Groq API key in the sidebar to continue")
77
+ st.sidebar.info("Don't have an API key? Sign up at [console.groq.com](https://console.groq.com)")
78
+
79
+ # Example problem display
80
+ st.markdown("### Example Problem")
81
+ st.markdown("""
82
+ ```
83
+ I have 5 bananas and 7 grapes. I eat 2 bananas and give away 3 grapes.
84
+ Then I buy a dozen apples and 2 packs of blueberries.
85
+ Each pack of blueberries contains 25 berries.
86
+ How many total pieces of fruit do I have at the end?
87
+ ```
88
+ """)
89
+ st.stop()
90
+
91
+ # Initialize LLM
92
+ try:
93
+ llm = ChatGroq(
94
+ model=selected_model,
95
+ groq_api_key=groq_api_key,
96
+ temperature=temperature,
97
+ streaming=True
98
+ )
99
+ except Exception as e:
100
+ st.error(f"Error initializing the AI model: {str(e)}")
101
+ st.stop()
102
+
103
+ # Initialize tools
104
+ def setup_tools():
105
+ """Initialize and return tools for the agent"""
106
+
107
+ # Wikipedia tool
108
+ wiki_wrapper = WikipediaAPIWrapper(top_k_results=2)
109
+ wiki_tool = WikipediaQueryRun(api_wrapper=wiki_wrapper)
110
+
111
+ # ArXiv tool for academic papers
112
+ arxiv_wrapper = ArxivAPIWrapper(top_k_results=1)
113
+ arxiv_tool = ArxivQueryRun(api_wrapper=arxiv_wrapper)
114
+
115
+ # DuckDuckGo search tool
116
+ search_tool = DuckDuckGoSearchRun()
117
+
118
+ # Math calculation tool
119
+ llm_math_chain = LLMMathChain.from_llm(llm=llm)
120
+ calculator = Tool(
121
+ func=llm_math_chain.run,
122
+ name="Calculator",
123
+ description="A tool for performing mathematical calculations. Input only mathematical expressions."
124
+ )
125
+
126
+ # Reasoning tool for detailed explanations
127
+ prompt = """
128
+ You're an expert mathematics teacher. Solve the following problem step by step:
129
+
130
+ {question}
131
+
132
+ First, identify what information is given and what is being asked.
133
+ Then, lay out a clear strategy for solving the problem.
134
+ Show your work carefully, with each step clearly labeled.
135
+ Provide a final answer with appropriate units if applicable.
136
+
137
+ Your solution:
138
+ """
139
+ prompt_template = PromptTemplate(
140
+ input_variables=["question"],
141
+ template=prompt
142
+ )
143
+ chain = LLMChain(llm=llm, prompt=prompt_template)
144
+ reasoning_tool = Tool(
145
+ name="MathReasoning",
146
+ func=chain.run,
147
+ description="A tool for solving math problems step-by-step with detailed explanations."
148
+ )
149
+
150
+ return [wiki_tool, arxiv_tool, search_tool, calculator, reasoning_tool]
151
+
152
+ # Set up the agent
153
+ def initialize_math_agent(tools):
154
+ """Initialize the math problem solving agent"""
155
+ system_message = SystemMessage(content="""
156
+ You are an expert mathematics tutor and problem solver. Your goal is to:
157
+ 1. Solve mathematical problems accurately
158
+ 2. Provide clear, step-by-step explanations
159
+ 3. Use the appropriate tools for calculations and information gathering
160
+ 4. Organize your answers in a structured format with headings
161
+ 5. Include formulas and equations where relevant
162
+
163
+ For math problems, always show your work and explain your thinking.
164
+ For information queries, cite your sources where appropriate.
165
+ """)
166
+
167
+ return initialize_agent(
168
+ tools=tools,
169
+ llm=llm,
170
+ agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
171
+ verbose=show_reasoning,
172
+ handle_parsing_errors=True,
173
+ system_message=system_message,
174
+ early_stopping_method="generate"
175
+ )
176
+
177
+ # Initialize chat session state
178
+ if "messages" not in st.session_state:
179
+ st.session_state["messages"] = [
180
+ {"role": "assistant", "content": "Hi, I'm your Math Problem Solver! Ask me any math question or problem, and I'll solve it step-by-step."}
181
+ ]
182
+
183
+ # Display chat history
184
+ for msg in st.session_state.messages:
185
+ st.chat_message(msg["role"]).write(msg['content'])
186
+
187
+ # Example problems for the user to try
188
+ example_problems = [
189
+ "Solve for x: 2x + 5 = 15",
190
+ "Find the area of a circle with radius 4 cm",
191
+ "If a train travels at 60 mph and takes 3 hours to reach its destination, how far did it travel?",
192
+ "I have 5 bananas and 7 grapes. I eat 2 bananas and give away 3 grapes. Then I buy a dozen apples and 2 packs of blueberries. Each pack contains 25 berries. How many total pieces of fruit do I have at the end?"
193
+ ]
194
+
195
+ # User input area with tabs for different input methods
196
+ tab1, tab2 = st.tabs(["Enter Your Question", "Try Examples"])
197
+
198
+ with tab1:
199
+ question = st.text_area(
200
+ "Type your math problem or question:",
201
+ placeholder="Enter your math problem here...",
202
+ height=100
203
+ )
204
+ solve_button = st.button("Solve Problem", type="primary")
205
+
206
+ with tab2:
207
+ st.write("Select an example problem:")
208
+ for i, example in enumerate(example_problems):
209
+ if st.button(f"Example {i+1}", key=f"example_{i}"):
210
+ question = example
211
+ solve_button = True
212
+ st.session_state.messages.append({"role": "user", "content": question})
213
+ st.experimental_rerun()
214
+
215
+ # Process the request when button is clicked
216
+ if solve_button and question:
217
+ # Add user message to chat
218
+ st.session_state.messages.append({"role": "user", "content": question})
219
+ st.chat_message("user").write(question)
220
+
221
+ # Initialize tools and agent
222
+ tools = setup_tools()
223
+ assistant_agent = initialize_math_agent(tools)
224
+
225
+ # Generate response with callback handler for streaming
226
+ with st.chat_message("assistant"):
227
+ st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=show_reasoning)
228
+ try:
229
+ response = assistant_agent.run(question, callbacks=[st_cb])
230
+ st.write(response)
231
+
232
+ # Add assistant response to chat
233
+ st.session_state.messages.append({'role': 'assistant', "content": response})
234
+ except Exception as e:
235
+ error_msg = f"Error generating response: {str(e)}"
236
+ st.error(error_msg)
237
+ st.session_state.messages.append({'role': 'assistant', "content": error_msg})
238
+
239
+ # Add footer
240
+ st.sidebar.markdown("---")
241
+ st.sidebar.markdown("### About")
242
+ st.sidebar.info(
243
+ "This app uses Groq's AI models to solve math problems "
244
+ "and provide step-by-step explanations. It can handle a wide range "
245
+ "of mathematical topics from basic arithmetic to advanced calculus."
246
+ )
247
+ st.sidebar.markdown("### Feedback")
248
+ st.sidebar.markdown("[Report an issue](https://github.com/yourusername/math-problem-solver/issues)")
readme.md ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ๐Ÿงฎ Math Problem Solver
2
+
3
+ ## Overview
4
+
5
+ Math Problem Solver is an AI-powered Streamlit application that helps users solve mathematical problems with step-by-step explanations. The application uses Groq's AI models (including Google Gemma 2) to provide detailed solutions to a wide range of mathematical topics.
6
+
7
+ ## Getting Started
8
+
9
+ ### Prerequisites
10
+
11
+ - Python 3.8+
12
+ - Groq API key (get one at [console.groq.com](https://console.groq.com/keys))
13
+
14
+ ### Installation
15
+
16
+ 1. Clone this repository:
17
+ ```bash
18
+ git clone https://github.com/yourusername/math-problem-solver.git
19
+ cd math-problem-solver
20
+ ```
21
+
22
+ 2. Install dependencies:
23
+ ```bash
24
+ pip install -r requirements.txt
25
+ ```
26
+
27
+ 3. Create a `.env` file in the project root and add your Groq API key:
28
+ ```
29
+ GROQ_API_KEY=your_api_key_here
30
+ ```
31
+
32
+ 4. Run the application:
33
+ ```bash
34
+ streamlit run app.py
35
+ ```
36
+
37
+ 5. Open your browser and navigate to `http://localhost:8501`
38
+
39
+ ## Usage
40
+
41
+ 1. Enter your Groq API key in the sidebar (if not already set in `.env`)
42
+ 2. Select your preferred AI model
43
+ 3. Type your math problem in the text area or choose from the example problems
44
+ 4. Click "Solve Problem" to get a detailed solution
45
+ 5. Review the step-by-step explanation
46
+
47
+ ### Example Problems
48
+
49
+ - Solve for x: 2x + 5 = 15
50
+ - Find the area of a circle with radius 4 cm
51
+ - If a train travels at 60 mph and takes 3 hours to reach its destination, how far did it travel?
52
+ - Word problems involving multiple operations and conversions
53
+
54
+ ## Technical Details
55
+
56
+ This application uses:
57
+
58
+ - **Streamlit**: For the web interface
59
+ - **LangChain**: For agent orchestration and tool integration
60
+ - **Groq API**: For AI model inference
61
+ - **Google Gemma 2**: Primary AI model for solving math problems
62
+ - **Wikipedia API**: For foundational knowledge
63
+ - **arXiv API**: For academic mathematical concepts
64
+ - **DuckDuckGo Search**: For web search capabilities
65
+
66
+ The application uses a zero-shot agent that strategically chooses which tool to use based on the problem type.
67
+
68
+ ## Advanced Configuration
69
+
70
+ In the "Advanced Options" section of the sidebar, you can:
71
+
72
+ - Adjust the temperature (creativity) of the AI responses
73
+ - Toggle the visibility of AI reasoning steps
74
+ - Select different models for different types of problems
75
+
76
+ ## Development
77
+
78
+ ### Project Structure
79
+
80
+ ```
81
+ math-problem-solver/
82
+ โ”œโ”€โ”€ app.py # Main application file
83
+ โ”œโ”€โ”€ .env # Environment variables (git-ignored)
84
+ โ”œโ”€โ”€ requirements.txt # Dependencies
85
+ โ”œโ”€โ”€ README.md # Project documentation
86
+ โ”œโ”€โ”€ LICENSE # MIT License
87
+ โ”œโ”€โ”€ screenshots/ # App screenshots
88
+ โ”‚ โ””โ”€โ”€ app_screenshot.png # Main app screenshot
89
+ โ””โ”€โ”€ .gitignore # Git ignore configuration
90
+ ```
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core dependencies
2
+ streamlit>=1.28.0
3
+ langchain>=0.1.0
4
+ langchain-groq>=0.1.0
5
+ python-dotenv>=1.0.0
6
+
7
+ # Tool dependencies
8
+ langchain-community>=0.0.10
9
+ wikipedia>=1.4.0
10
+ arxiv>=1.4.7
11
+ duckduckgo-search>=3.9.0
12
+ numpy>=1.24.0
13
+ sympy>=1.12.0
14
+
15
+ # Utility dependencies
16
+ protobuf>=4.25.1