masadonline commited on
Commit
fdcadd7
Β·
verified Β·
1 Parent(s): 113a87d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -24
app.py CHANGED
@@ -50,6 +50,30 @@ 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
  def generate_answer_with_groq(question, context, retries=3, delay=2):
54
  url = "https://api.groq.com/openai/v1/chat/completions"
55
  api_key = os.environ["GROQ_API_KEY"]
@@ -80,6 +104,8 @@ def generate_answer_with_groq(question, context, retries=3, delay=2):
80
  else:
81
  return f"⚠️ Groq API Error: {str(e)}"
82
 
 
 
83
  # --- Twilio Chat Handlers ---
84
  def fetch_latest_incoming_message(account_sid, auth_token, conversation_sid):
85
  client = Client(account_sid, auth_token)
@@ -137,29 +163,20 @@ if all([account_sid, auth_token, conversation_sid, GROQ_API_KEY]):
137
 
138
  index, embedding_model, text_chunks = setup_knowledge_base()
139
 
140
- st.success("βœ… Knowledge base ready. Monitoring WhatsApp every 5 seconds...")
141
-
142
- # --- Auto-refresh logic ---
143
- st.markdown("""
144
- <meta http-equiv="refresh" content="5">
145
- """, unsafe_allow_html=True)
146
-
147
- if "last_msg_index" not in st.session_state:
148
- st.session_state.last_msg_index = -1
149
-
150
- with st.spinner("Checking for new WhatsApp messages..."):
151
- question, sender, msg_index = fetch_latest_incoming_message(account_sid, auth_token, conversation_sid)
152
- if question and msg_index != st.session_state.last_msg_index:
153
- st.info(f"πŸ“₯ New Question from {sender}:\n\n> {question}")
154
- relevant_chunks = retrieve_chunks(question, index, embedding_model, text_chunks)
155
- context = "\n\n".join(relevant_chunks)
156
- answer = generate_answer_with_groq(question, context)
157
- send_twilio_message(account_sid, auth_token, conversation_sid, answer)
158
- st.success("πŸ“€ Answer sent via WhatsApp!")
159
- st.markdown(f"### ✨ Answer:\n\n{answer}")
160
- st.session_state.last_msg_index = msg_index
161
- else:
162
- st.write("⏳ No new WhatsApp queries found.")
163
-
164
  else:
165
  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"]
 
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):
111
  client = Client(account_sid, auth_token)
 
163
 
164
  index, embedding_model, text_chunks = setup_knowledge_base()
165
 
166
+ st.success("βœ… Knowledge base ready. Monitoring WhatsApp...")
167
+
168
+ if st.button("πŸ” Check for New WhatsApp Query"):
169
+ with st.spinner("Checking messages..."):
170
+ question, sender, msg_index = fetch_latest_incoming_message(account_sid, auth_token, conversation_sid)
171
+ if question:
172
+ st.info(f"πŸ“₯ New Question from {sender}:\n\n> {question}")
173
+ relevant_chunks = retrieve_chunks(question, index, embedding_model, text_chunks)
174
+ context = "\n\n".join(relevant_chunks)
175
+ answer = generate_answer_with_groq(question, context)
176
+ send_twilio_message(account_sid, auth_token, conversation_sid, answer)
177
+ st.success("πŸ“€ Answer sent via WhatsApp!")
178
+ st.markdown(f"### ✨ Answer:\n\n{answer}")
179
+ else:
180
+ st.warning("No new messages from users found.")
 
 
 
 
 
 
 
 
 
181
  else:
182
  st.warning("❗ Please provide all required credentials.")