Ashkchamp commited on
Commit
3e26e5f
·
verified ·
1 Parent(s): 493a898

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -36
app.py CHANGED
@@ -6,6 +6,7 @@ from langchain_community.utilities import WikipediaAPIWrapper
6
  from langchain.agents.agent_types import AgentType
7
  from langchain.agents import Tool, initialize_agent
8
  from langchain.callbacks import StreamlitCallbackHandler
 
9
 
10
  # Set up Streamlit page configuration
11
  st.set_page_config(page_title="General Knowledge Assistant", page_icon="🧭")
@@ -18,49 +19,66 @@ if not groq_api_key:
18
  st.info("Please add your Groq API key to continue")
19
  st.stop()
20
 
21
- # Initialize the LLM (Groq API - llama-3.1-70b)
 
22
  llm = ChatGroq(model="meta-llama/llama-4-maverick-17b-128e-instruct", groq_api_key=groq_api_key)
23
 
24
  # Initialize Wikipedia tool for information retrieval
25
- wikipedia_wrapper = WikipediaAPIWrapper()
26
  wikipedia_tool = Tool(
27
- name="Wikipedia",
28
  func=wikipedia_wrapper.run,
29
- description="A tool for searching the Internet to find information on various topics, including general knowledge."
 
 
 
 
30
  )
31
 
32
- # Prompt template for general knowledge questions
33
- prompt = """
34
- You are a knowledgeable assistant. Your task is to answer the user's questions accurately, using your general knowledge.
35
- If the answer is not readily available in your knowledge base, search Wikipedia for relevant information.
36
- Your information should be accurate and up to date.Whenever I tell you to write essay give a title also to the essay.
37
- Question: {question}
 
 
 
 
 
38
  Answer:
39
  """
40
 
41
  # Initialize the prompt template
42
  prompt_template = PromptTemplate(
43
  input_variables=["question"],
44
- template=prompt
45
  )
46
 
47
- # Combine all the tools into a chain for answering general knowledge questions
48
  chain = LLMChain(llm=llm, prompt=prompt_template)
49
 
50
  # Reasoning tool for logic-based or factual questions
51
  reasoning_tool = Tool(
52
- name="Reasoning tool",
53
  func=chain.run,
54
- description="A tool for answering general knowledge questions using logical reasoning and factual information.Try to use the latest information"
 
 
 
55
  )
56
 
57
  # Initialize the agent with the tools and LLM
 
58
  assistant_agent = initialize_agent(
59
  tools=[wikipedia_tool, reasoning_tool],
60
  llm=llm,
61
  agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
62
- verbose=False,
63
- handle_parsing_errors=True
 
 
 
64
  )
65
 
66
  # Initialize session state for message history if it doesn't exist
@@ -73,23 +91,45 @@ if "messages" not in st.session_state:
73
  for msg in st.session_state.messages:
74
  st.chat_message(msg["role"]).write(msg['content'])
75
 
76
- # Get the user's question
77
- question = st.text_area("Enter your question:", "Please enter your general knowledge question here")
78
-
79
- # Handle the button click to process the question
80
- if st.button("find my answer"):
81
- if question:
82
- with st.spinner("Generate response.."):
83
- st.session_state.messages.append({"role":"user","content":question})
84
- st.chat_message("user").write(question)
85
-
86
- st_cb=StreamlitCallbackHandler(st.container(),expand_new_thoughts=False)
87
- response=assistant_agent.run(st.session_state.messages,callbacks=[st_cb]
88
- )
89
- st.session_state.messages.append({'role':'assistant',"content":response})
90
- st.write('### Response:')
91
- st.success(response)
92
-
93
- else:
94
- st.warning("Please enter the question")
95
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  from langchain.agents.agent_types import AgentType
7
  from langchain.agents import Tool, initialize_agent
8
  from langchain.callbacks import StreamlitCallbackHandler
9
+ import datetime # Import datetime to add current date context
10
 
11
  # Set up Streamlit page configuration
12
  st.set_page_config(page_title="General Knowledge Assistant", page_icon="🧭")
 
19
  st.info("Please add your Groq API key to continue")
20
  st.stop()
21
 
22
+ # Initialize the LLM (Using the model from your original code)
23
+ # You might consider trying 'llama3-70b-8192' if Maverick struggles with tool selection
24
  llm = ChatGroq(model="meta-llama/llama-4-maverick-17b-128e-instruct", groq_api_key=groq_api_key)
25
 
26
  # Initialize Wikipedia tool for information retrieval
27
+ wikipedia_wrapper = WikipediaAPIWrapper(top_k_results=2, doc_content_chars_max=2000) # Limit results slightly
28
  wikipedia_tool = Tool(
29
+ name="Wikipedia Search", # Renamed slightly for clarity
30
  func=wikipedia_wrapper.run,
31
+ description=(
32
+ "Use this tool to find specific information, facts, or details about people, places, events, or topics. "
33
+ "It is especially useful for getting CURRENT and UP-TO-DATE information or checking facts that might change over time. "
34
+ "Input should be a clear search query."
35
+ )
36
  )
37
 
38
+ # Prompt template for general knowledge questions (used by the Reasoning Tool)
39
+ # Added a note about the current date to potentially help the LLM contextualize recency
40
+ current_date = datetime.datetime.now().strftime("%Y-%m-%d")
41
+ prompt_text = f"""
42
+ You are a knowledgeable assistant. The current date is {current_date}.
43
+ Your task is to answer the user's questions accurately using your general knowledge.
44
+ If you are asked to write an essay, please provide a title for the essay.
45
+ Your information should be accurate and up-to-date based on your internal knowledge cutoff.
46
+ If you suspect your internal knowledge might be outdated for the question, mention that the information might not be the absolute latest.
47
+
48
+ Question: {{question}}
49
  Answer:
50
  """
51
 
52
  # Initialize the prompt template
53
  prompt_template = PromptTemplate(
54
  input_variables=["question"],
55
+ template=prompt_text
56
  )
57
 
58
+ # Create the LLMChain for the Reasoning tool
59
  chain = LLMChain(llm=llm, prompt=prompt_template)
60
 
61
  # Reasoning tool for logic-based or factual questions
62
  reasoning_tool = Tool(
63
+ name="General Knowledge and Reasoning", # Renamed slightly for clarity
64
  func=chain.run,
65
+ description=(
66
+ "Use this tool to answer general knowledge questions, perform reasoning tasks, or explain concepts based on the AI's internal knowledge base. "
67
+ "This tool relies on the AI's trained data, which might have a knowledge cut-off date. Do NOT use this tool if the question likely requires very recent information (use Wikipedia Search instead)."
68
+ )
69
  )
70
 
71
  # Initialize the agent with the tools and LLM
72
+ # Ensure verbose=False and handle_parsing_errors=True as per your original code
73
  assistant_agent = initialize_agent(
74
  tools=[wikipedia_tool, reasoning_tool],
75
  llm=llm,
76
  agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
77
+ verbose=False, # Set to True temporarily if you need to debug the agent's thought process
78
+ handle_parsing_errors=True,
79
+ # Add max_iterations to prevent potential infinite loops if the agent gets stuck
80
+ max_iterations=5,
81
+ early_stopping_method="generate" # Stop generating if it thinks it's done
82
  )
83
 
84
  # Initialize session state for message history if it doesn't exist
 
91
  for msg in st.session_state.messages:
92
  st.chat_message(msg["role"]).write(msg['content'])
93
 
94
+ # Get the user's question (using st.chat_input for better UI)
95
+ if user_query := st.chat_input("Please enter your general knowledge question here"):
96
+ # Add user message to state and display it
97
+ st.session_state.messages.append({"role": "user", "content": user_query})
98
+ st.chat_message("user").write(user_query)
99
+
100
+ # Format the input for the agent - pass only the latest user query
101
+ # Include conversation history *if* the agent type supports it well,
102
+ # but ZERO_SHOT_REACT_DESCRIPTION primarily focuses on the latest input.
103
+ # We will pass only the user_query for simplicity and correctness with .run()
104
+ agent_input = user_query
105
+
106
+ # Add context about the conversation history potentially (optional, advanced)
107
+ # agent_input = f"Previous conversation:\n{st.session_state.messages}\n\n Current question: {user_query}"
108
+
109
+ # Generate and display response
110
+ with st.chat_message("assistant"):
111
+ st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
112
+ # *** FIX: Pass only the user_query string to the agent's run method ***
113
+ response = assistant_agent.run(agent_input, callbacks=[st_cb])
114
+ st.session_state.messages.append({"role": "assistant", "content": response})
115
+ st.write(response) # Display the final response
116
+
117
+ # Note: Removed the text_area + button combo in favor of st.chat_input for a cleaner chat interface.
118
+ # If you prefer the text_area and button:
119
+ # user_question = st.text_area("Enter your question:", "Please enter your general knowledge question here", key="user_q_input")
120
+ # if st.button("Find my answer", key="submit_q"):
121
+ # if user_question and user_question != "Please enter your general knowledge question here":
122
+ # # Add user message to state and display it
123
+ # st.session_state.messages.append({"role": "user", "content": user_question})
124
+ # st.chat_message("user").write(user_question)
125
+
126
+ # agent_input = user_question # Use the text_area content
127
+
128
+ # # Generate and display response
129
+ # with st.chat_message("assistant"):
130
+ # st_cb = StreamlitCallbackHandler(st.container(), expand_new_thoughts=False)
131
+ # response = assistant_agent.run(agent_input, callbacks=[st_cb])
132
+ # st.session_state.messages.append({"role": "assistant", "content": response})
133
+ # st.write(response)
134
+ # else:
135
+ # st.warning("Please enter a question.")