Okay, let's enhance your Streamlit chatbot to handle greetings and clarify the suggestion of related FAQs for vague questions.
The good news is that your code already includes the logic for suggesting related FAQs when the confidence score is below 0.85 (the else block within if matches: for FAQ classification). We just need to ensure the greeting part is added.
Here's the updated code:
import streamlit as st
from qdrant_client import QdrantClient
from sentence_transformers import SentenceTransformer
import requests
import sqlite3
# --- Configuration ---
QDRANT_HOST = "localhost" # Use "localhost" or your actual Qdrant host
QDRANT_PORT = 6333
MISTRAL_API_URL = "http://localhost:11434/api/generate"
SQLITE_DB_PATH = "logistics.db"
FAQ_COLLECTION_NAME = "shypbuddy_faq_embeddings"
# 🧠 Load embedding model
@st.cache_resource
def load_model():
"""Loads and caches the SentenceTransformer model."""
return SentenceTransformer("all-MiniLM-L6-v2")
model = load_model()
# 🔗 Connect to Qdrant (FAQ vector DB)
@st.cache_resource
def connect_qdrant():
"""Connects to Qdrant client."""
return QdrantClient(host=QDRANT_HOST, port=QDRANT_PORT)
client = connect_qdrant()
# 🔗 Connect to your live database (SQLite example)
@st.cache_resource
def connect_sqlite():
"""Connects to SQLite database."""
return sqlite3.connect(SQLITE_DB_PATH, check_same_thread=False) # check_same_thread=False for Streamlit
conn = connect_sqlite()
# 🤖 Helper to call Mistral API
def query_mistral(prompt):
"""Sends a prompt to the local Mistral API and returns the response."""
try:
res = requests.post(MISTRAL_API_URL, json={
"model": "mistral",
"prompt": prompt,
"stream": False
})
res.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return res.json().get("response", "").strip()
except requests.exceptions.ConnectionError:
return f"⚠️ Error: Could not connect to Mistral API at {MISTRAL_API_URL}. Please ensure it's running."
except requests.exceptions.HTTPError as e:
return f"⚠️ Error from Mistral API: {e}. Response: {res.text}"
except Exception as e:
return f"⚠️ An unexpected error occurred with Mistral API: {e}"
# 🎯 Step 1: Classify user input intent with improved prompt
def classify_input(user_input):
"""Classifies user input as FAQ or LIVE_DATA using Mistral."""
prompt = (
"You are a classification model.\n"
"Classify the following user input into exactly one of two categories:\n"
" - FAQ : if the user is asking general questions about logistics or ShypBuddy service, policies, or general information.\n"
" - LIVE_DATA : if the user is asking about their specific shipment status, tracking info, or requires live data retrieval using a tracking number or specific details.\n"
"\n"
"Only respond with exactly one word: FAQ or LIVE_DATA.\n"
"If the input is vague, unclear, or doesn't fit either category, classify it as UNKNOWN.\n"
"\n"
f"User Input: \"{user_input}\"\n"
"Classification:"
)
classification = query_mistral(prompt).strip().upper()
if classification not in ["FAQ", "LIVE_DATA", "UNKNOWN"]:
# Fallback for unexpected Mistral responses
classification = "UNKNOWN"
return classification
# 🔍 FAQ semantic search
def search_faq(query):
"""Searches the Qdrant FAQ collection for relevant answers."""
query_vector = model.encode([query])[0].tolist()
results = client.search(
collection_name=FAQ_COLLECTION_NAME,
query_vector=query_vector,
limit=3, # Get top 3 to offer choices for vague questions
with_payload=True,
# score_threshold=0.7 # Keep this commented out or adjust based on your data quality
# It can sometimes be too restrictive.
# We'll use score to decide between direct answer vs. suggestions.
)
return results
# 🔄 Step 2: Generate SQL query from user input using Mistral
def generate_sql_query(user_input):
"""Generates a SQL query from user input for live data retrieval."""
# Add a more robust schema definition for Mistral
schema_info = """
Table: shipments
Columns:
- tracking_number TEXT PRIMARY KEY (e.g., 'SHYP12345')
- status TEXT (e.g., 'In Transit', 'Delivered', 'Pending', 'Exception')
- location TEXT (e.g., 'New York', 'Warehouse A', 'Local Hub')
- eta TEXT (Estimated Time of Arrival, e.g., '2023-12-31 10:00 AM')
"""
prompt = (
"You are an assistant that converts user shipment tracking or logistics queries into safe SQL queries. "
"Only generate SELECT queries for the 'shipments' table. "
"Ensure the query includes 'tracking_number', 'status', 'location', and 'eta' in the SELECT clause. "
"Strictly use the available columns from the 'shipments' table. "
"If a tracking number is not explicitly mentioned but implied, try to infer it from common patterns if possible, otherwise state 'NO_TRACKING_NUMBER'. "
"If the query cannot be safely or meaningfully converted to SQL, reply with 'NO_SQL'.\n\n"
f"Database Schema:\n{schema_info}\n\n"
f"User question: \"{user_input}\"\n"
"SQL query:"
)
sql_query = query_mistral(prompt)
if "NO_SQL" in sql_query or "NO_TRACKING_NUMBER" in sql_query or not sql_query.strip().upper().startswith("SELECT"):
return None
return sql_query.strip()
# 🗄 Execute SQL and format response
def query_live_data(user_input):
"""Executes a generated SQL query and formats the response."""
sql_query = generate_sql_query(user_input)
if not sql_query:
return (
"❗ Sorry, I couldn't generate a valid shipment tracking SQL query for that. "
"Please provide a specific tracking number or clearer details about the shipment you are asking about."
)
try:
cursor = conn.cursor()
cursor.execute(sql_query)
row = cursor.fetchone()
if not row:
return "❗ No shipment found matching your query. Please double-check the tracking number or details."
# Ensure correct column order based on your SELECT statement generation
# Assuming generate_sql_query always selects tracking_number, status, location, eta
tracking_number, status, location, eta = row
response = (
f"📦 Shipment **{tracking_number}** is currently **'{status}'**, "
f"located at '{location}', with an estimated arrival time of **{eta}**."
)
return response
except sqlite3.OperationalError as e:
return f"⚠️ Database Error: {e}. The generated SQL might be malformed or table/column names incorrect. (SQL: `{sql_query}`)"
except Exception as e:
return f"⚠️ An error occurred while fetching live data: {e}"
# --- Streamlit UI ---
st.set_page_config(page_title="ShypBuddy Chatbot", page_icon="📦")
st.title("📦 ShypBuddy Logistic Chatbot (FAQ + Live Data with Mistral)")
st.info("I can answer general logistics questions or provide real-time updates on your shipments. Just ask!")
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "last_matches" not in st.session_state:
st.session_state.last_matches = []
# Display chat history first
for role, message in st.session_state.chat_history:
if role == "user":
st.markdown(f"🧑💻 **You**: {message}")
else:
st.markdown(f"🤖 **Bot**: {message}")
# Input form for new messages
with st.form("chat_form", clear_on_submit=True):
user_input = st.text_input("Enter your logistics question or shipment query", key="user_input_text")
submitted = st.form_submit_button("Send")
if submitted and user_input:
st.session_state.chat_history.append(("user", user_input))
# Clear previous matches when a new query is submitted
st.session_state.last_matches = []
# --- New: Handle Greetings ---
lower_input = user_input.lower().strip()
greetings = ["hi", "hello", "hey", "hallo", "good morning", "good afternoon", "good evening", "how are you", "what's up"]
if any(greeting in lower_input for greeting in greetings):
reply = "👋 Hello there! How can I assist you with your ShypBuddy logistics today?"
st.session_state.chat_history.append(("bot", reply))
else:
# Proceed with classification for non-greeting inputs
classification = classify_input(user_input)
# DEBUG: show classification result in UI (can remove or comment out after debugging)
st.write(f"**_DEBUG: Classification result = '{classification}'_**")
if classification == "LIVE_DATA":
reply = query_live_data(user_input)
st.session_state.chat_history.append(("bot", reply))
elif classification == "FAQ":
matches = search_faq(user_input)
if matches:
top_score = matches[0].score
top_payload = matches[0].payload
# Confidence threshold for direct answer vs. suggestions
if top_score >= 0.85: # High confidence, answer directly
st.session_state.chat_history.append(("bot", f"✅ {top_payload['answer']}"))
else:
# Vague question, show list of FAQs to choose from
st.session_state.chat_history.append(("bot", "🔍 I found some related FAQs that might help. Please select one of the questions below to get its answer:"))
st.session_state.last_matches = matches # Store matches for displaying buttons
else:
st.session_state.chat_history.append(("bot", "🚫 Sorry, I couldn't find any related logistics FAQs for your query. Can you rephrase or ask something else?"))
else: # UNKNOWN classification
st.session_state.chat_history.append(("bot", "🤔 I'm not sure how to respond to that. I can help with general logistics FAQs or specific shipment tracking questions. Can you clarify?"))
# --- Display FAQ choices if available ---
# This part needs to be outside the 'if submitted' block to persist button display
if st.session_state.last_matches:
st.markdown("---") # Separator for clarity
st.markdown("**Suggested FAQs:**")
for idx, match in enumerate(st.session_state.last_matches, 1):
# Use a unique key for each button to prevent issues when matches change
if st.button(f"{idx}. {match.payload['question']}", key=f"faq_button_{idx}_{match.id}"):
# When a button is clicked, treat it as a new user input (for chat history)
st.session_state.chat_history.append(("user", f"Selected FAQ: {match.payload['question']}"))
st.session_state.chat_history.append(("bot", f"✅ Answer: {match.payload['answer']}"))
st.session_state.last_matches = [] # Clear choices after one is selected
st.experimental_rerun() # Rerun to update chat history and clear buttons
# Important: Rerun the app after processing a submission to update the chat history display
if submitted and user_input:
st.experimental_rerun()
Key Changes and Improvements:
-
Greeting Handling:
- A new
if any(greeting in lower_input for greeting in greetings): block is added right after a user submits input.
- If the input matches a common greeting, a friendly welcome message is displayed, and the classification process is skipped.
-
FAQ Vague Question Suggestions (Clarification):
- The existing logic (
if top_score >= 0.85: vs. else:) for deciding between a direct answer and suggesting related FAQs is retained.
- The prompt when suggesting FAQs has been slightly rephphrased for better clarity:
"🔍 I found some related FAQs that might help. Please select one of the questions below to get its answer:"
- Crucially, the
st.session_state.last_matches = [] is added when a new query is submitted to clear out any old suggestions.
- A unique
key is added to the FAQ suggestion buttons (key=f"faq_button_{idx}_{match.id}") to prevent potential Streamlit re-rendering issues, especially when the list of suggestions changes.
- When a suggested FAQ button is clicked, it logs the selection in the chat history (
st.session_state.chat_history.append(("user", f"Selected FAQ: {match.payload['question']}"))) before providing the answer.
-
Enhanced Mistral Prompts and Error Handling:
- The
classify_input prompt now includes UNKNOWN as a possible classification if the input is vague, providing a fallback for unhandled queries.
- The
generate_sql_query prompt now explicitly provides a mini-schema for the shipments table, which can help Mistral generate more accurate SQL. It also handles cases where no tracking number can be inferred.
- Improved
requests error handling for the Mistral API to differentiate between connection errors and HTTP errors.
- Added specific
sqlite3.OperationalError handling to query_live_data for better database error reporting.
-
Minor UI/UX Improvements:
st.set_page_config for a page title and icon.
st.info message at the start.
st.markdown("---") separator for suggested FAQs.
check_same_thread=False added to sqlite3.connect for better compatibility with Streamlit's threading model.
Before Running:
- Ensure
logistics.db exists and has a shipments table with tracking_number, status, location, eta columns.
- If you don't have one, create a dummy one:
import sqlite3
conn = sqlite3.connect("logistics.db")
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS shipments (
tracking_number TEXT PRIMARY KEY,
status TEXT,
location TEXT,
eta TEXT
)
""")
cursor.execute("INSERT OR REPLACE INTO shipments (tracking_number, status, location, eta) VALUES ('SHYP12345', 'In Transit', 'Chicago', '2023-12-25 09:00 AM')")
cursor.execute("INSERT OR REPLACE INTO shipments (tracking_number, status, location, eta) VALUES ('SHIP98765', 'Delivered', 'New York', '2023-12-20 02:30 PM')")
conn.commit()
conn.close()
Run this once separately, then delete the code.
- Ensure Qdrant is running and your
shypbuddy_faq_embeddings collection is populated.
- Ensure Mistral is running on
http://localhost:11434 with the mistral model loaded (e.g., using Ollama).
ollama run mistral or ollama pull mistral if not downloaded.
ollama serve to ensure the API is active.
This enhanced version should provide a more robust and user-friendly chatbot experience!