talsen89 commited on
Commit
f5468e6
·
verified ·
1 Parent(s): 831eb06

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +177 -183
app.py CHANGED
@@ -1,184 +1,178 @@
1
- import streamlit as st
2
- import os
3
- import base64
4
- from dotenv import load_dotenv
5
- from langchain_groq import ChatGroq
6
- from langchain.chains import LLMMathChain, LLMChain
7
- from langchain.prompts import PromptTemplate
8
- from langchain_community.utilities import WikipediaAPIWrapper
9
- from langchain.agents.agent_types import AgentType
10
- from langchain.agents import Tool, initialize_agent
11
- from langchain_community.callbacks.streamlit import StreamlitCallbackHandler
12
- from groq import Groq
13
-
14
- # Load environment variables
15
- load_dotenv()
16
- groq_api_key = os.getenv("GROQ_API_KEY")
17
-
18
- if not groq_api_key:
19
- st.error("Groq API Key not found in .env file")
20
- st.stop()
21
-
22
- # Set up the Streamlit app
23
- st.set_page_config(page_title="Math Solver", page_icon="👨‍🔬")
24
- st.title("Math Solver")
25
-
26
- # Initialize the LLM for text questions
27
- llm_text = ChatGroq(model="gemma2-9b-it", groq_api_key=groq_api_key)
28
-
29
- # Initialize the LLM for image questions
30
- llm_image = ChatGroq(model="llama-3.2-90b-vision-preview", groq_api_key=groq_api_key)
31
-
32
- # Initializing the tools for text questions
33
- wikipedia_wrapper = WikipediaAPIWrapper()
34
- wikipedia_tool = Tool(
35
- name="Wikipedia",
36
- func=wikipedia_wrapper.run,
37
- description="A tool for searching the Internet to find various information on the topics mentioned."
38
- )
39
-
40
- # Initialize the Math tool for text questions
41
- math_chain = LLMMathChain.from_llm(llm=llm_text)
42
- calculator = Tool(
43
- name="Calculator",
44
- func=math_chain.run,
45
- description="A tool for solving mathematical problems. Provide only the mathematical expressions."
46
- )
47
-
48
- prompt = """
49
- You are a mathematical problem-solving assistant tasked with helping users solve their questions. Arrive at the solution logically, providing a clear and step-by-step explanation. Present your response in a structured point-wise format for better understanding.
50
- Question: {question}
51
- Answer:
52
- """
53
-
54
- prompt_template = PromptTemplate(
55
- input_variables=["question"],
56
- template=prompt
57
- )
58
-
59
- # Combine all the tools into a chain for text questions
60
- chain = LLMChain(llm=llm_text, prompt=prompt_template)
61
-
62
- reasoning_tool = Tool(
63
- name="Reasoning Tool",
64
- func=chain.run,
65
- description="A tool for answering logic-based and reasoning questions."
66
- )
67
-
68
- # Initialize the agents for text questions
69
- assistant_agent_text = initialize_agent(
70
- tools=[wikipedia_tool, calculator, reasoning_tool],
71
- llm=llm_text,
72
- agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
73
- verbose=False,
74
- handle_parsing_errors=True
75
- )
76
-
77
- if "messages" not in st.session_state:
78
- st.session_state["messages"] = [
79
- {"role": "assistant", "content": "Welcome! I am your Assistant. How can I help you today?"}
80
- ]
81
-
82
- for msg in st.session_state.messages:
83
- if msg["role"] == "user" and "image" in msg:
84
- st.chat_message(msg["role"]).write(msg['content'])
85
- st.image(msg["image"], caption='Uploaded Image', use_column_width=True)
86
- else:
87
- st.chat_message(msg["role"]).write(msg['content'])
88
-
89
- # Sidebar for navigation
90
- st.sidebar.header("Navigation")
91
- if st.sidebar.button("Text Question"):
92
- st.session_state["section"] = "text"
93
- if st.sidebar.button("Image Question"):
94
- st.session_state["section"] = "image"
95
-
96
- # Main content area
97
- if "section" not in st.session_state:
98
- st.session_state["section"] = "text"
99
-
100
- def clean_response(response):
101
- # Clean and format the response from the LLM
102
- if "```" in response:
103
- response = response.split("```")[1].strip()
104
- return response
105
-
106
- if st.session_state["section"] == "text":
107
- st.header("Text Question")
108
- st.write("Please enter your mathematical question below, and I will provide a detailed solution.")
109
- question = st.text_area("Your Question:", "Example: I have 5 apples and 3 oranges. If I eat 2 apples, how many fruits do I have left?")
110
-
111
- if st.button("Get Answer"):
112
- if question:
113
- with st.spinner("Generating response..."):
114
- st.session_state.messages.append({"role": "user", "content": question})
115
- st.chat_message("user").write(question)
116
-
117
- st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
118
- try:
119
- response = assistant_agent_text.run(st.session_state.messages, callbacks=[st_cb])
120
- cleaned_response = clean_response(response)
121
- st.session_state.messages.append({'role': 'assistant', "content": cleaned_response})
122
- st.write('### Response:')
123
- st.success(cleaned_response)
124
- except ValueError as e:
125
- st.error(f"An error occurred: {e}")
126
- else:
127
- st.warning("Please enter a question to get an answer.")
128
-
129
- elif st.session_state["section"] == "image":
130
- st.header("Image Question")
131
- st.write("Please enter your question below and upload an image. I will provide a detailed solution.")
132
- question = st.text_area("Your Question:", "Example: What will be the answer?")
133
- uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
134
-
135
- if st.button("Get Answer"):
136
- if question and uploaded_file is not None:
137
- with st.spinner("Generating response..."):
138
- image_data = uploaded_file.read()
139
- image_data_url = f"data:image/jpeg;base64,{base64.b64encode(image_data).decode()}"
140
- st.session_state.messages.append({"role": "user", "content": question, "image": image_data})
141
- st.chat_message("user").write(question)
142
- st.image(image_data, caption='Uploaded Image', use_column_width=True)
143
-
144
- # Initialize Groq client
145
- client = Groq()
146
-
147
- # Prepare the messages for the Groq API
148
- messages = [
149
- {
150
- "role": "user",
151
- "content": [
152
- {
153
- "type": "text",
154
- "text": question
155
- },
156
- {
157
- "type": "image_url",
158
- "image_url": {
159
- "url": image_data_url
160
- }
161
- }
162
- ]
163
- }
164
- ]
165
-
166
- try:
167
- completion = client.chat.completions.create(
168
- model="llama-3.2-90b-vision-preview",
169
- messages=messages,
170
- temperature=1,
171
- max_tokens=1024,
172
- top_p=1,
173
- stream=False,
174
- stop=None,
175
- )
176
- response = completion.choices[0].message.content
177
- cleaned_response = clean_response(response)
178
- st.session_state.messages.append({'role': 'assistant', "content": cleaned_response})
179
- st.write('### Response:')
180
- st.success(cleaned_response)
181
- except ValueError as e:
182
- st.error(f"An error occurred: {e}")
183
- else:
184
  st.warning("Please enter a question and upload an image to get an answer.")
 
1
+ import streamlit as st
2
+ import os
3
+ import base64
4
+ from dotenv import load_dotenv
5
+ from langchain_openai import OpenAI
6
+ from langchain.chains import LLMMathChain, LLMChain
7
+ from langchain.prompts import PromptTemplate
8
+ from langchain_community.utilities import WikipediaAPIWrapper
9
+ from langchain.agents.agent_types import AgentType
10
+ from langchain.agents import Tool, initialize_agent
11
+ from langchain_community.callbacks.streamlit import StreamlitCallbackHandler
12
+ from groq import Groq
13
+
14
+ load_dotenv()
15
+ groq_api_key = os.getenv("GROQ_API_KEY")
16
+
17
+ if not groq_api_key:
18
+ st.error("Groq API Key not found in .env file")
19
+ st.stop()
20
+
21
+ st.set_page_config(page_title="Math Solver", page_icon="👨‍🔬")
22
+ st.title("Math Solver")
23
+
24
+ llm_text = OpenAI(model='gpt-3.5-turbo-instruct', temperature=0)
25
+ llm_image = ChatGroq(model="llama-3.2-90b-vision-preview", groq_api_key=groq_api_key)
26
+
27
+ wikipedia_wrapper = WikipediaAPIWrapper()
28
+ wikipedia_tool = Tool(
29
+ name="Wikipedia",
30
+ func=wikipedia_wrapper.run,
31
+ description="A tool for searching the Internet to find various information on the topics mentioned."
32
+ )
33
+
34
+ math_chain = LLMMathChain.from_llm(llm=llm_text)
35
+ calculator = Tool(
36
+ name="Calculator",
37
+ func=math_chain.run,
38
+ description="A tool for solving mathematical problems. Provide only the mathematical expressions."
39
+ )
40
+
41
+ word_problem_template = """You are a reasoning agent tasked with solving the user's logic-based questions.
42
+ Logically arrive at the solution, and be factual. In your answers, clearly detail the steps involved and give
43
+ the final answer. Provide the response in bullet points. Question: {question} Answer:"""
44
+
45
+ math_assistant_prompt = PromptTemplate(
46
+ input_variables=["question"],
47
+ template=word_problem_template
48
+ )
49
+
50
+ word_problem_chain = LLMChain(llm=llm_text, prompt=math_assistant_prompt)
51
+ reasoning_tool = Tool.from_function(
52
+ name="Reasoning Tool",
53
+ func=word_problem_chain.run,
54
+ description="Useful for when you need to answer logic-based/reasoning questions."
55
+ )
56
+
57
+ assistant_agent_text = initialize_agent(
58
+ tools=[wikipedia_tool, calculator, reasoning_tool],
59
+ llm=llm_text,
60
+ agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
61
+ verbose=False,
62
+ handle_parsing_errors=True
63
+ )
64
+
65
+ if "messages" not in st.session_state:
66
+ st.session_state["messages"] = [
67
+ {"role": "assistant", "content": "Welcome! I am your Assistant. How can I help you today?"}
68
+ ]
69
+
70
+ for msg in st.session_state.messages:
71
+ if msg["role"] == "user" and "image" in msg:
72
+ st.chat_message(msg["role"]).write(msg['content'])
73
+ st.image(msg["image"], caption='Uploaded Image', use_column_width=True)
74
+ else:
75
+ st.chat_message(msg["role"]).write(msg['content'])
76
+
77
+ st.sidebar.header("Navigation")
78
+ if st.sidebar.button("Text Question"):
79
+ st.session_state["section"] = "text"
80
+ if st.sidebar.button("Image Question"):
81
+ st.session_state["section"] = "image"
82
+
83
+ if "section" not in st.session_state:
84
+ st.session_state["section"] = "text"
85
+
86
+ def clean_response(response):
87
+ if "```" in response:
88
+ response = response.split("```")[1].strip()
89
+ return response
90
+
91
+ if st.session_state["section"] == "text":
92
+ st.header("Text Question")
93
+ st.write("Please enter your mathematical question below, and I will provide a detailed solution.")
94
+ question = st.text_area("Your Question:", "Example: I have 5 apples and 3 oranges. If I eat 2 apples, how many fruits do I have left?")
95
+
96
+ if st.button("Get Answer"):
97
+ if question:
98
+ with st.spinner("Generating response..."):
99
+ st.session_state.messages.append({"role": "user", "content": question})
100
+ st.chat_message("user").write(question)
101
+
102
+ st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
103
+ try:
104
+ response = assistant_agent_text.run(st.session_state.messages, callbacks=[st_cb])
105
+ cleaned_response = clean_response(response)
106
+ st.session_state.messages.append({'role': 'assistant', "content": cleaned_response})
107
+ st.write('### Response:')
108
+ st.success(cleaned_response)
109
+ except ValueError as e:
110
+ st.error(f"An error occurred: {e}")
111
+ else:
112
+ st.warning("Please enter a question to get an answer.")
113
+
114
+ elif st.session_state["section"] == "image":
115
+ st.header("Image Question")
116
+ st.write("Please enter your question below and upload an image. I will provide a detailed solution.")
117
+ question = st.text_area("Your Question:", "Example: What will be the answer?")
118
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg", "png"])
119
+
120
+ if st.button("Get Answer"):
121
+ if question and uploaded_file is not None:
122
+ with st.spinner("Generating response..."):
123
+ image_data = uploaded_file.read()
124
+ image_data_url = f"data:image/jpeg;base64,{base64.b64encode(image_data).decode()}"
125
+ st.session_state.messages.append({"role": "user", "content": question, "image": image_data})
126
+ st.chat_message("user").write(question)
127
+ st.image(image_data, caption='Uploaded Image', use_column_width=True)
128
+
129
+ client = Groq()
130
+
131
+ messages = [
132
+ {
133
+ "role": "user",
134
+ "content": [
135
+ {
136
+ "type": "text",
137
+ "text": question
138
+ },
139
+ {
140
+ "type": "image_url",
141
+ "image_url": {
142
+ "url": image_data_url
143
+ }
144
+ }
145
+ ]
146
+ }
147
+ ]
148
+
149
+ try:
150
+ completion = client.chat.completions.create(
151
+ model="llama-3.2-90b-vision-preview",
152
+ messages=messages,
153
+ temperature=1,
154
+ max_tokens=1024,
155
+ top_p=1,
156
+ stream=False,
157
+ stop=None,
158
+ )
159
+ extracted_text = completion.choices[0].message.content
160
+
161
+ # Send the extracted text to the tools for further processing
162
+ st.session_state.messages.append({"role": "user", "content": extracted_text})
163
+ st.chat_message("user").write(extracted_text)
164
+
165
+ st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
166
+ try:
167
+ response = assistant_agent_text.run(extracted_text, callbacks=[st_cb])
168
+ cleaned_response = clean_response(response)
169
+ st.session_state.messages.append({'role': 'assistant', "content": cleaned_response})
170
+ st.write('### Response:')
171
+ st.success(cleaned_response)
172
+ except ValueError as e:
173
+ st.error(f"An error occurred: {e}")
174
+
175
+ except ValueError as e:
176
+ st.error(f"An error occurred: {e}")
177
+ else:
 
 
 
 
 
 
178
  st.warning("Please enter a question and upload an image to get an answer.")