Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -50,72 +50,42 @@ def retrieve_chunks(question, index, embed_model, text_chunks, k=3):
|
|
50 |
D, I = index.search(np.array([question_embedding]), k)
|
51 |
return [text_chunks[i] for i in I[0]]
|
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 |
-
def chunk_text(text, tokenizer, chunk_size=150, chunk_overlap=30):
|
77 |
-
tokens = tokenizer.tokenize(text)
|
78 |
-
chunks, start = [], 0
|
79 |
-
while start < len(tokens):
|
80 |
-
end = min(start + chunk_size, len(tokens))
|
81 |
-
chunk_tokens = tokens[start:end]
|
82 |
-
chunks.append(tokenizer.convert_tokens_to_string(chunk_tokens))
|
83 |
-
start += chunk_size - chunk_overlap
|
84 |
-
return chunks
|
85 |
-
|
86 |
-
def retrieve_chunks(question, index, embed_model, text_chunks, k=3):
|
87 |
-
question_embedding = embed_model.encode([question])[0]
|
88 |
-
D, I = index.search(np.array([question_embedding]), k)
|
89 |
-
return [text_chunks[i] for i in I[0]]
|
90 |
-
|
91 |
-
# Generate answer using Groq API with retries and timeout
|
92 |
def generate_answer_with_groq(question, context, retries=3, delay=2):
|
93 |
url = "https://api.groq.com/openai/v1/chat/completions"
|
94 |
-
api_key = os.environ
|
95 |
-
if not api_key:
|
96 |
-
return "⚠️ GROQ_API_KEY not set."
|
97 |
-
|
98 |
headers = {
|
99 |
"Authorization": f"Bearer {api_key}",
|
100 |
"Content-Type": "application/json",
|
101 |
}
|
102 |
-
prompt =
|
103 |
-
f"Customer asked: '{question}'\n\n"
|
104 |
-
f"Here is the relevant product or policy info to help:\n{context}\n\n"
|
105 |
-
f"Respond in a friendly and helpful tone as a toy shop support agent."
|
106 |
-
)
|
107 |
payload = {
|
108 |
"model": "llama3-8b-8192",
|
109 |
"messages": [
|
110 |
-
{
|
111 |
-
"role": "system",
|
112 |
-
"content": (
|
113 |
-
"You are ToyBot, a friendly and helpful WhatsApp assistant for an online toy shop. "
|
114 |
-
"Your goal is to politely answer customer questions, help them choose the right toys, "
|
115 |
-
"provide order or delivery information, explain return policies, and guide them through purchases. "
|
116 |
-
"Always sound warm, helpful, and trustworthy like a professional customer support agent."
|
117 |
-
)
|
118 |
-
},
|
119 |
{"role": "user", "content": prompt},
|
120 |
],
|
121 |
"temperature": 0.5,
|
@@ -124,18 +94,17 @@ def generate_answer_with_groq(question, context, retries=3, delay=2):
|
|
124 |
|
125 |
for attempt in range(retries):
|
126 |
try:
|
127 |
-
response = requests.post(url, headers=headers, json=payload
|
128 |
-
response.raise_for_status()
|
129 |
result = response.json()
|
130 |
return result['choices'][0]['message']['content'].strip()
|
131 |
-
except
|
132 |
-
if
|
133 |
time.sleep(delay)
|
134 |
continue
|
135 |
else:
|
136 |
-
return f"⚠️ Groq API
|
137 |
-
|
138 |
-
|
139 |
|
140 |
# --- Twilio Chat Handlers ---
|
141 |
def fetch_latest_incoming_message(account_sid, auth_token, conversation_sid):
|
@@ -158,22 +127,20 @@ def send_twilio_message(account_sid, auth_token, conversation_sid, body):
|
|
158 |
st.set_page_config(page_title="SMEHelpBot – WhatsApp Integration", layout="wide")
|
159 |
st.title("📱 SMEHelpBot + WhatsApp (via Twilio)")
|
160 |
|
161 |
-
# Load from secrets
|
162 |
account_sid = st.secrets.get("TWILIO_SID")
|
163 |
auth_token = st.secrets.get("TWILIO_TOKEN")
|
|
|
164 |
GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
|
165 |
|
166 |
-
# Fallback for
|
167 |
if not all([account_sid, auth_token, GROQ_API_KEY]):
|
168 |
st.warning("⚠️ Some secrets not found. Please enter missing credentials below:")
|
169 |
account_sid = st.text_input("Twilio SID", value=account_sid or "")
|
170 |
auth_token = st.text_input("Twilio Auth Token", type="password", value=auth_token or "")
|
171 |
GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")
|
172 |
|
173 |
-
|
174 |
-
conversation_sid = st.text_input("Twilio Conversation SID")
|
175 |
-
|
176 |
-
if all([account_sid, auth_token, GROQ_API_KEY, conversation_sid]):
|
177 |
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
|
178 |
|
179 |
@st.cache_resource
|
@@ -212,4 +179,4 @@ if all([account_sid, auth_token, GROQ_API_KEY, conversation_sid]):
|
|
212 |
else:
|
213 |
st.warning("No new messages from users found.")
|
214 |
else:
|
215 |
-
st.warning("❗ Please provide all required credentials
|
|
|
50 |
D, I = index.search(np.array([question_embedding]), k)
|
51 |
return [text_chunks[i] for i in I[0]]
|
52 |
|
53 |
+
#def generate_answer_with_groq(question, context, retries=3, delay=2):
|
54 |
+
# prompt = f"Based on the following context, answer the question: '{question}'\n\nContext:\n{context}"
|
55 |
+
# groq_client = Groq(api_key=os.environ["GROQ_API_KEY"])
|
56 |
+
|
57 |
+
# for attempt in range(retries):
|
58 |
+
# try:
|
59 |
+
# response = groq_client.chat.completions.create(
|
60 |
+
# model="llama3-8b-8192",
|
61 |
+
# messages=[
|
62 |
+
# {"role": "system", "content": "You are an AI Assistant for Small Businesses."},
|
63 |
+
# {"role": "user", "content": prompt},
|
64 |
+
# ]
|
65 |
+
# )
|
66 |
+
# return response.choices[0].message.content
|
67 |
+
# except GroqError as e:
|
68 |
+
# if "503" in str(e) and attempt < retries - 1:
|
69 |
+
# time.sleep(delay)
|
70 |
+
# continue
|
71 |
+
# else:
|
72 |
+
# return f"⚠️ Groq API Error: {str(e)}"
|
73 |
+
|
74 |
+
#-----------------------------------------
|
75 |
+
import requests # ✅ Add this at the top of your file
|
76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
def generate_answer_with_groq(question, context, retries=3, delay=2):
|
78 |
url = "https://api.groq.com/openai/v1/chat/completions"
|
79 |
+
api_key = os.environ["GROQ_API_KEY"]
|
|
|
|
|
|
|
80 |
headers = {
|
81 |
"Authorization": f"Bearer {api_key}",
|
82 |
"Content-Type": "application/json",
|
83 |
}
|
84 |
+
prompt = f"Based on the following context, answer the question: '{question}'\n\nContext:\n{context}"
|
|
|
|
|
|
|
|
|
85 |
payload = {
|
86 |
"model": "llama3-8b-8192",
|
87 |
"messages": [
|
88 |
+
{"role": "system", "content": "You are a real human and you will respond as real human. You will be asked questions and you will respond like a human."},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
{"role": "user", "content": prompt},
|
90 |
],
|
91 |
"temperature": 0.5,
|
|
|
94 |
|
95 |
for attempt in range(retries):
|
96 |
try:
|
97 |
+
response = requests.post(url, headers=headers, json=payload)
|
|
|
98 |
result = response.json()
|
99 |
return result['choices'][0]['message']['content'].strip()
|
100 |
+
except Exception as e:
|
101 |
+
if "503" in str(e) and attempt < retries - 1:
|
102 |
time.sleep(delay)
|
103 |
continue
|
104 |
else:
|
105 |
+
return f"⚠️ Groq API Error: {str(e)}"
|
106 |
+
|
107 |
+
#-----------------------------------------
|
108 |
|
109 |
# --- Twilio Chat Handlers ---
|
110 |
def fetch_latest_incoming_message(account_sid, auth_token, conversation_sid):
|
|
|
127 |
st.set_page_config(page_title="SMEHelpBot – WhatsApp Integration", layout="wide")
|
128 |
st.title("📱 SMEHelpBot + WhatsApp (via Twilio)")
|
129 |
|
130 |
+
# Load from Hugging Face secrets
|
131 |
account_sid = st.secrets.get("TWILIO_SID")
|
132 |
auth_token = st.secrets.get("TWILIO_TOKEN")
|
133 |
+
conversation_sid = "CHe065d01a6b654ca0a698bfb849c980de"
|
134 |
GROQ_API_KEY = st.secrets.get("GROQ_API_KEY")
|
135 |
|
136 |
+
# Fallback for testing
|
137 |
if not all([account_sid, auth_token, GROQ_API_KEY]):
|
138 |
st.warning("⚠️ Some secrets not found. Please enter missing credentials below:")
|
139 |
account_sid = st.text_input("Twilio SID", value=account_sid or "")
|
140 |
auth_token = st.text_input("Twilio Auth Token", type="password", value=auth_token or "")
|
141 |
GROQ_API_KEY = st.text_input("GROQ API Key", type="password", value=GROQ_API_KEY or "")
|
142 |
|
143 |
+
if all([account_sid, auth_token, conversation_sid, GROQ_API_KEY]):
|
|
|
|
|
|
|
144 |
os.environ["GROQ_API_KEY"] = GROQ_API_KEY
|
145 |
|
146 |
@st.cache_resource
|
|
|
179 |
else:
|
180 |
st.warning("No new messages from users found.")
|
181 |
else:
|
182 |
+
st.warning("❗ Please provide all required credentials.")
|