Ashkchamp commited on
Commit
1b36021
·
verified ·
1 Parent(s): aef6f53

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -50
app.py CHANGED
@@ -1,82 +1,85 @@
 
 
1
  import streamlit as st
2
-
3
  from langchain_groq import ChatGroq
4
  from langchain.chains import LLMChain
5
  from langchain.prompts import PromptTemplate
6
  from langchain_community.utilities import WikipediaAPIWrapper
 
7
  from langchain.agents.agent_types import AgentType
8
  from langchain.agents import Tool, initialize_agent
9
  from langchain.callbacks import StreamlitCallbackHandler
10
 
 
 
 
 
 
 
 
 
11
  st.set_page_config(page_title="General Knowledge Assistant", page_icon="🧭")
12
  st.title("General Knowledge Assistant")
13
 
14
- groq_api_key = st.sidebar.text_input(label="Groq API Key", type="password")
15
-
16
- if not groq_api_key:
17
- st.info("Please add your Groq API key to continue")
18
- st.stop()
19
-
20
- llm = ChatGroq(model="meta-llama/llama-4-maverick-17b-128e-instruct", groq_api_key=groq_api_key)
21
 
 
22
  wikipedia_wrapper = WikipediaAPIWrapper()
23
  wikipedia_tool = Tool(
24
  name="Wikipedia",
25
  func=wikipedia_wrapper.run,
26
- description="Use this tool to fetch updated information from the internet when your base knowledge is outdated or incomplete."
27
  )
28
 
29
- prompt = """
30
- You are a knowledgeable assistant. Your task is to answer the user's questions accurately with your general knowledge.
31
- If you detect that your stored information is outdated or missing recent details, immediately search Wikipedia for updated info.
32
- Always ensure your answer is up to date. Whenever I tell you to write essay give a title also to the essay.
33
-
34
- Question: {question}
35
- Answer:
36
- """
37
-
38
- prompt_template = PromptTemplate(
39
- input_variables=["question"],
40
- template=prompt
41
  )
42
 
 
 
 
 
 
 
43
  chain = LLMChain(llm=llm, prompt=prompt_template)
44
 
45
- reasoning_tool = Tool(
46
- name="Reasoning tool",
47
- func=chain.run,
48
- description="A tool for answering general knowledge questions using logical reasoning and factual information. Use Wikipedia if your answer might be outdated."
49
- )
50
-
51
- assistant_agent = initialize_agent(
52
- tools=[wikipedia_tool, reasoning_tool],
53
- llm=llm,
54
- agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
55
- verbose=False,
56
- handle_parsing_errors=True
57
- )
58
-
59
  if "messages" not in st.session_state:
60
  st.session_state["messages"] = [
61
  {"role": "assistant", "content": "Hi, I'm your general knowledge assistant. Feel free to ask me any question!"}
62
  ]
63
 
64
- for msg in st.session_state.messages:
65
- st.chat_message(msg["role"]).write(msg['content'])
66
 
67
- question = st.text_area("Enter your question:", "Please enter your general knowledge question here")
 
68
 
69
- if st.button("find my answer"):
70
  if question:
71
- with st.spinner("Generate response.."):
72
- st.session_state.messages.append({"role": "user", "content": question})
73
- st.chat_message("user").write(question)
74
-
75
- st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
76
- response = assistant_agent.run(st.session_state.messages, callbacks=[st_cb])
77
-
78
- st.session_state.messages.append({"role": "assistant", "content": response})
79
- st.write("### Response:")
80
- st.success(response)
81
  else:
82
- st.warning("Please enter the question")
 
1
+ import os
2
+ from dotenv import load_dotenv
3
  import streamlit as st
 
4
  from langchain_groq import ChatGroq
5
  from langchain.chains import LLMChain
6
  from langchain.prompts import PromptTemplate
7
  from langchain_community.utilities import WikipediaAPIWrapper
8
+ from langchain_community.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper
9
  from langchain.agents.agent_types import AgentType
10
  from langchain.agents import Tool, initialize_agent
11
  from langchain.callbacks import StreamlitCallbackHandler
12
 
13
+ # Load .env
14
+ load_dotenv()
15
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
16
+ if not GROQ_API_KEY:
17
+ st.error("GROQ_API_KEY not found in environment")
18
+ st.stop()
19
+
20
+ # Streamlit UI
21
  st.set_page_config(page_title="General Knowledge Assistant", page_icon="🧭")
22
  st.title("General Knowledge Assistant")
23
 
24
+ # Initialize LLM
25
+ llm = ChatGroq(
26
+ model="meta-llama/llama-4-maverick-17b-128e-instruct",
27
+ groq_api_key=GROQ_API_KEY
28
+ )
 
 
29
 
30
+ # Wikipedia tool
31
  wikipedia_wrapper = WikipediaAPIWrapper()
32
  wikipedia_tool = Tool(
33
  name="Wikipedia",
34
  func=wikipedia_wrapper.run,
35
+ description="Fetch summaries from Wikipedia."
36
  )
37
 
38
+ # DuckDuckGo web search tool
39
+ ddg_wrapper = DuckDuckGoSearchAPIWrapper()
40
+ web_search_tool = Tool(
41
+ name="WebSearch",
42
+ func=ddg_wrapper.run,
43
+ description="Perform a live web search via DuckDuckGo."
 
 
 
 
 
 
44
  )
45
 
46
+ # Prompt template
47
+ prompt = """
48
+ You are a knowledgeable assistant. Answer {question} using your internal knowledge.
49
+ If you’re unsure, think the info may be outdated, or can’t find it, simply say "I don't know" or "Outdated".
50
+ """
51
+ prompt_template = PromptTemplate(input_variables=["question"], template=prompt)
52
  chain = LLMChain(llm=llm, prompt=prompt_template)
53
 
54
+ # Fallback logic: LLM → DuckDuckGo → Wikipedia
55
+ def get_answer(query: str) -> str:
56
+ lm_answer = chain.run({"question": query}).strip()
57
+ if any(flag in lm_answer.lower() for flag in ["i don't know", "outdated", "not sure"]):
58
+ web_ans = ddg_wrapper.run(query)
59
+ if web_ans and len(web_ans) > 20:
60
+ return web_ans
61
+ return wikipedia_wrapper.run(query)
62
+ return lm_answer
63
+
64
+ # Conversation history
 
 
 
65
  if "messages" not in st.session_state:
66
  st.session_state["messages"] = [
67
  {"role": "assistant", "content": "Hi, I'm your general knowledge assistant. Feel free to ask me any question!"}
68
  ]
69
 
70
+ for msg in st.session_state["messages"]:
71
+ st.chat_message(msg["role"]).write(msg["content"])
72
 
73
+ # User input
74
+ question = st.text_area("Enter your question:", "")
75
 
76
+ if st.button("Find my answer"):
77
  if question:
78
+ st.session_state["messages"].append({"role": "user", "content": question})
79
+ st.chat_message("user").write(question)
80
+ with st.spinner("Generating response..."):
81
+ answer = get_answer(question)
82
+ st.session_state["messages"].append({"role": "assistant", "content": answer})
83
+ st.chat_message("assistant").write(answer)
 
 
 
 
84
  else:
85
+ st.warning("Please enter a question.")