Update app.py
Browse files
app.py
CHANGED
@@ -10,25 +10,22 @@ import re
|
|
10 |
from langchain.docstore.document import Document
|
11 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
12 |
from langchain_community.retrievers import BM25Retriever
|
13 |
-
|
14 |
-
from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, ManagedAgent
|
15 |
-
from smolagents.agents import ToolCallingAgent
|
16 |
-
from smolagents import Tool, HfApiModel, TransformersModel, LiteLLMModel
|
17 |
-
from typing import Optional
|
18 |
import gradio as gr
|
19 |
import logging
|
20 |
from nltk.corpus import words
|
21 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
22 |
from sklearn.metrics.pairwise import cosine_similarity
|
23 |
|
|
|
|
|
|
|
24 |
|
|
|
25 |
if 'GROQ_API_KEY' not in os.environ or not os.environ['GROQ_API_KEY']:
|
26 |
os.environ['GROQ_API_KEY'] = getpass.getpass('Enter GROQ_API_KEY: ')
|
27 |
else:
|
28 |
print("GROQ_API_KEY is already set.")
|
29 |
-
# Set up logging
|
30 |
-
logging.basicConfig(level=logging.INFO)
|
31 |
-
logger = logging.getLogger(__name__)
|
32 |
|
33 |
# Load NLTK word list for valid word checks
|
34 |
try:
|
@@ -153,7 +150,6 @@ class RetrieverTool(Tool):
|
|
153 |
def forward(self, query: str) -> str:
|
154 |
assert isinstance(query, str), "Search query must be a string."
|
155 |
docs = self.retriever.invoke(query)
|
156 |
-
# Return only the content of the most relevant document
|
157 |
if docs:
|
158 |
return docs[0].page_content.strip()
|
159 |
else:
|
@@ -161,54 +157,56 @@ class RetrieverTool(Tool):
|
|
161 |
|
162 |
retriever_tool = RetrieverTool(docs_processed)
|
163 |
|
|
|
|
|
|
|
164 |
# Define the improved custom prompt
|
165 |
custom_prompt = """
|
166 |
-
You are a friendly and knowledgeable
|
167 |
|
168 |
When answering:
|
169 |
-
1.
|
170 |
-
2. Highlight key points in an easy-to-understand manner.
|
171 |
-
3. Include examples, tips, or short
|
172 |
-
4. Format
|
173 |
-
5.
|
174 |
-
|
175 |
-
Answer each question in a similar concise, helpful, and friendly way.
|
176 |
"""
|
177 |
|
178 |
# Define the agent using smolagents
|
179 |
-
model =
|
180 |
agent = CodeAgent(
|
181 |
-
tools=[retriever_tool], model=model, max_iterations=4, verbose=True
|
182 |
)
|
183 |
|
184 |
# Gradio interface for interacting with the RAG pipeline
|
185 |
def gradio_interface(query):
|
186 |
try:
|
|
|
187 |
is_valid, message = is_valid_input(query)
|
188 |
if not is_valid:
|
189 |
return message
|
190 |
|
191 |
-
# Perform similarity search
|
192 |
similar, similar_question, similarity_score = similarity_search(query, corpus_questions, threshold=0.2)
|
193 |
-
if
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
)
|
199 |
-
|
200 |
-
# Directly query the agent if the question is valid
|
201 |
-
return agent.run(f"{custom_prompt}\n\nQuestion: {query}").strip()
|
202 |
except Exception as e:
|
203 |
logger.error(f"Error during query processing: {e}")
|
204 |
return "**An error occurred while processing your request. Please try again later.**"
|
205 |
|
|
|
|
|
206 |
interface = gr.Interface(
|
207 |
fn=gradio_interface,
|
208 |
inputs=gr.Textbox(label="Enter your question", placeholder="e.g., How does box breathing help reduce anxiety?"),
|
209 |
outputs=gr.Markdown(label="Answer"),
|
210 |
-
title="AI Chatbot
|
211 |
-
description="Ask
|
212 |
theme="compact"
|
213 |
)
|
214 |
|
|
|
10 |
from langchain.docstore.document import Document
|
11 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
12 |
from langchain_community.retrievers import BM25Retriever
|
13 |
+
from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool
|
|
|
|
|
|
|
|
|
14 |
import gradio as gr
|
15 |
import logging
|
16 |
from nltk.corpus import words
|
17 |
from sklearn.feature_extraction.text import TfidfVectorizer
|
18 |
from sklearn.metrics.pairwise import cosine_similarity
|
19 |
|
20 |
+
# Set up logging
|
21 |
+
logging.basicConfig(level=logging.INFO)
|
22 |
+
logger = logging.getLogger("Daily Wellness AI Guru")
|
23 |
|
24 |
+
# Securely input the GROQ API key
|
25 |
if 'GROQ_API_KEY' not in os.environ or not os.environ['GROQ_API_KEY']:
|
26 |
os.environ['GROQ_API_KEY'] = getpass.getpass('Enter GROQ_API_KEY: ')
|
27 |
else:
|
28 |
print("GROQ_API_KEY is already set.")
|
|
|
|
|
|
|
29 |
|
30 |
# Load NLTK word list for valid word checks
|
31 |
try:
|
|
|
150 |
def forward(self, query: str) -> str:
|
151 |
assert isinstance(query, str), "Search query must be a string."
|
152 |
docs = self.retriever.invoke(query)
|
|
|
153 |
if docs:
|
154 |
return docs[0].page_content.strip()
|
155 |
else:
|
|
|
157 |
|
158 |
retriever_tool = RetrieverTool(docs_processed)
|
159 |
|
160 |
+
# Define DuckDuckGoSearchTool
|
161 |
+
duckduckgo_search_tool = DuckDuckGoSearchTool()
|
162 |
+
|
163 |
# Define the improved custom prompt
|
164 |
custom_prompt = """
|
165 |
+
You are Daily Wellness AI Guru, a friendly and knowledgeable assistant here to simplify wellness. Your goal is to provide clear, concise, and actionable answers to the user's health and wellness-related questions. Mention how Daily Wellness AI offers tailored solutions for day-to-day wellness tasks. Use a warm and friendly tone to make the user feel at ease.
|
166 |
|
167 |
When answering:
|
168 |
+
1. Address the user warmly with "Hello! This is Daily Wellness AI Guru."
|
169 |
+
2. Highlight the key points in an easy-to-understand manner.
|
170 |
+
3. Include practical examples, tips, or short guides where relevant.
|
171 |
+
4. Format the response for clarity using markdown (e.g., numbered lists, bullet points).
|
172 |
+
5. Reinforce how Daily Wellness AI helps simplify wellness through AI-powered solutions.
|
173 |
+
6. End with an engaging and polite closing remark that invites further questions.
|
|
|
174 |
"""
|
175 |
|
176 |
# Define the agent using smolagents
|
177 |
+
model = HfApiModel("groq/llama3-8b-8192") # Ensure the model is available
|
178 |
agent = CodeAgent(
|
179 |
+
tools=[retriever_tool, duckduckgo_search_tool], model=model, max_iterations=4, verbose=True
|
180 |
)
|
181 |
|
182 |
# Gradio interface for interacting with the RAG pipeline
|
183 |
def gradio_interface(query):
|
184 |
try:
|
185 |
+
# Validate input
|
186 |
is_valid, message = is_valid_input(query)
|
187 |
if not is_valid:
|
188 |
return message
|
189 |
|
190 |
+
# Perform similarity search
|
191 |
similar, similar_question, similarity_score = similarity_search(query, corpus_questions, threshold=0.2)
|
192 |
+
if similar:
|
193 |
+
response = agent.run(f"{custom_prompt}\n\nQuestion: {query}")
|
194 |
+
return response.strip()
|
195 |
+
else:
|
196 |
+
response = duckduckgo_search_tool.invoke(query)
|
197 |
+
return f"{response.strip()}\n\nRemember, Daily Wellness AI is here to simplify wellness with AI-powered solutions. Feel free to ask more questions!"
|
|
|
|
|
|
|
198 |
except Exception as e:
|
199 |
logger.error(f"Error during query processing: {e}")
|
200 |
return "**An error occurred while processing your request. Please try again later.**"
|
201 |
|
202 |
+
|
203 |
+
# Create the Gradio interface
|
204 |
interface = gr.Interface(
|
205 |
fn=gradio_interface,
|
206 |
inputs=gr.Textbox(label="Enter your question", placeholder="e.g., How does box breathing help reduce anxiety?"),
|
207 |
outputs=gr.Markdown(label="Answer"),
|
208 |
+
title="Daily Wellness AI Guru Chatbot",
|
209 |
+
description="Ask health and wellness questions. Get actionable, friendly advice from your wellness companion.",
|
210 |
theme="compact"
|
211 |
)
|
212 |
|