Update app.py
Browse files
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
|
| 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 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
st.
|
| 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 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
)
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
if st.
|
| 92 |
-
st.
|
| 93 |
-
|
| 94 |
-
st.
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
if
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
"
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
messages
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 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.")
|