SharanOO7/Math_problem_Solver
0
1import streamlit as st
2from langchain_groq import ChatGroq
3from langchain.chains import LLMChain
4from langchain.chains.llm_math.base import LLMMathChain
5from langchain.prompts import PromptTemplate
6from langchain_community.utilities import WikipediaAPIWrapper
7from langchain.agents.agent_types import AgentType
8from langchain.agents import Tool,initialize_agent
9from langchain.callbacks import StreamlitCallbackHandler
10import os
11from dotenv import load_dotenv
12load_dotenv()
13st.set_page_config(page_title='Text to math problem solver')
14st.title('Text to Math Problem solver')
15groq_api_key=st.text_input("Enter password:", type="password")
16if groq_api_key: #
17 llm=ChatGroq(model='Gemma2-9b-It',groq_api_key=groq_api_key)
18
19 wikipedia_wrapper=WikipediaAPIWrapper()
20 wikipedia_tool=Tool(name='wikipedia',func=wikipedia_wrapper.run,description='A Tool for searching the internet to find the various information about the topic')
21
22 math_chain=LLMMathChain.from_llm(llm=llm)
23 calculator=Tool(name='Calculator',func=math_chain.run,description='For answering only input mathematical expression need to be provided')
24 prompt='''
25 You are an expert math problem solver. For the given question, solve it step-by-step, explaining each logical step clearly. After reasoning, provide the final answer.
26 Question: {question}
27 Step-by-step solution:
28 '''
29
30 prompt_template=PromptTemplate(input_variables=['question'],template=prompt)
31
32 chain=LLMChain(llm=llm,prompt=prompt_template)
33
34 resoning_tool=Tool(name='Reasoning Tool',func=chain.run,description='For answering logic based and reasoning question')
35
36 assistant_agent=initialize_agent(tools=[wikipedia_tool,calculator,resoning_tool],llm=llm,agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,verbose=False,handle_parsing_errors=True)
37
38 if 'messages' not in st.session_state:
39 st.session_state['messages']=[{'role':'assistant','content':'Hi, I am a Math Chatbot who can answer all your math problems '}]
40
41 for msg in st.session_state.messages:
42 st.chat_message(msg['role']).write(msg['content'])
43
44 question=st.text_area('Enter your question ')
45
46 if st.button('find my answer'):
47 if question:
48 with st.spinner('Generating Response...'):
49 st.session_state.messages.append({'role':'user','content':question})
50 st.chat_message('user').write(question)
51
52 st_callback=StreamlitCallbackHandler(st.container(),expand_new_thoughts=False)
53 response=assistant_agent.run(st.session_state.messages,callbacks=[st_callback])
54 st.session_state.messages.append({'role':'assistant','content':response})
55 st.write('Response:')
56 st.success(response)
57 