|
1 | 1 | import streamlit as st |
| 2 | +import pandas as pd |
2 | 3 | from streamlit_chat import message |
3 | 4 | from langchain_community.document_loaders.csv_loader import CSVLoader |
4 | 5 | from langchain_community.embeddings import HuggingFaceEmbeddings |
5 | 6 | from langchain_community.vectorstores import FAISS |
6 | 7 | from langchain_community.llms import Ollama |
7 | 8 | from langchain.chains import ConversationalRetrievalChain |
| 9 | +import time |
8 | 10 |
|
9 | 11 | DB_FAISS_PATH = 'vectorstore/db_faiss' |
10 | 12 | CSV_FILE_PATH = r'dogs_cleaned.csv' # Replace with your CSV file path |
|
27 | 29 | def load_llm(): |
28 | 30 | # Load Mistral through Ollama |
29 | 31 | llm = Ollama( |
30 | | - # model="mistral", # Using Mistral 7B - a powerful open source model |
31 | | - model="phi", |
| 32 | + model="mistral", # Using Mistral 7B - a powerful open source model |
| 33 | + # model="phi", |
32 | 34 | temperature=0.5, |
33 | 35 | ) |
34 | 36 | return llm |
@@ -57,12 +59,66 @@ def load_and_process_data(): |
57 | 59 | # Load the chain once at startup |
58 | 60 | chain = load_and_process_data() |
59 | 61 |
|
| 62 | +def is_dog_related(query): |
| 63 | + # List of dog-related keywords |
| 64 | + dog_keywords = [ |
| 65 | + 'dog', 'breed', 'puppy', 'canine', 'hound', 'terrier', 'shepherd', |
| 66 | + 'retriever', 'poodle', 'bulldog', 'labrador', 'german', 'golden', |
| 67 | + 'bark', 'pet', 'training', 'grooming', 'walk', 'leash', 'collar', |
| 68 | + 'kennel', 'veterinary', 'vet', 'pup', 'pooch', 'dog breed', 'dog breeds', |
| 69 | + 'chew', 'bite', 'paw', 'paws', 'paw print', 'paw print', 'paw print', 'paw print', |
| 70 | + ] |
| 71 | + # read first column of csv file |
| 72 | + df = pd.read_csv(CSV_FILE_PATH) |
| 73 | + df = df.iloc[:, 0] |
| 74 | + # add all the values in the first column to the dog_keywords list as lowercase |
| 75 | + dog_keywords.extend(df.str.lower().tolist()) |
| 76 | + # Convert query to lowercase for case-insensitive matching |
| 77 | + query_lower = query.lower() |
| 78 | + |
| 79 | + # Check if any dog-related keyword is in the query |
| 80 | + return any(keyword in query_lower for keyword in dog_keywords) |
| 81 | + |
60 | 82 | def conversational_chat(query): |
| 83 | + current_time = time.time() |
| 84 | + |
| 85 | + # Rate limit check |
| 86 | + if 'last_query_time' in st.session_state: |
| 87 | + time_since_last_query = current_time - st.session_state.last_query_time |
| 88 | + if time_since_last_query < 10: |
| 89 | + remaining_time = int(10 - time_since_last_query) |
| 90 | + st.error(f"Rate limit exceeded! ⏳ Please wait {remaining_time} seconds before sending another message! This is to prevent abuse and overload my server. This rate limit is applied to all users. Resend you query to continue and Thanks for your patience!") |
| 91 | + return None |
| 92 | + |
| 93 | + # Check if query is dog-related |
| 94 | + if not is_dog_related(query): |
| 95 | + return "I am a dog breed expert assistant. I can only answer questions about dogs and dog breeds. Please ask me about dogs! 🐕" |
| 96 | + |
| 97 | + st.session_state.last_query_time = current_time |
| 98 | + |
61 | 99 | with st.spinner('🐾 Fetching response... Thank you for your patience! 🐕'): |
62 | | - # Add context about ratings to the query |
63 | | - context = """In the data, ratings are on a scale where higher numbers (like 5) mean the breed performs |
64 | | - better in that category, and lower numbers (like 1) mean the breed performs worse in that category. |
65 | | - Please consider this when answering. """ |
| 100 | + context = """You are a dog breed expert assistant. You must ONLY answer questions about dogs and dog breeds. |
| 101 | + If the question is not about dogs, respond with "I am a dog breed expert assistant. I can only answer questions about dogs and dog breeds." |
| 102 | +
|
| 103 | + These are the columns in the data: |
| 104 | + Breed Name,Detailed Description Link,Dog Size,Dog Breed Group,Height,"Avg. Height, cm",Weight,"Avg. Weight, kg",Life Span,"Avg. Life Span, years",Adaptability,Adapts Well To Apartment Living,Good For Novice Owners,Sensitivity Level,Tolerates Being Alone,Tolerates Cold Weather,Tolerates Hot Weather,All Around Friendliness,Affectionate With Family,Kid-Friendly,Dog Friendly,Friendly Toward Strangers,Health And Grooming Needs,Amount Of Shedding,Drooling Potential,Easy To Groom,General Health,Potential For Weight Gain,Size,Trainability,Easy To Train,Intelligence,Potential For Mouthiness,Prey Drive,Tendency To Bark Or Howl,Wanderlust Potential,Physical Needs,Energy Level,Intensity,Exercise Needs,Potential For Playfulness |
| 105 | +
|
| 106 | + The data contains ratings on a scale of 1-5 for columns (Adaptability, Adapts Well To Apartment Living, Good For Novice Owners, Sensitivity Level, Tolerates Being Alone, Tolerates Cold Weather, Tolerates Hot Weather, All Around Friendliness, Affectionate With Family, Kid-Friendly, Dog Friendly, Friendly Toward Strangers, Health And Grooming Needs, Amount Of Shedding, Drooling Potential, Easy To Groom, General Health, Potential For Weight Gain, Size, Trainability, Easy To Train, Intelligence, Potential For Mouthiness, Prey Drive, Tendency To Bark Or Howl, Wanderlust Potential, Physical Needs, Energy Level, Intensity, Exercise Needs, Potential For Playfulness) where: |
| 107 | + - 5 is the BEST/HIGHEST score (excellent) |
| 108 | + - 4 is ABOVE AVERAGE |
| 109 | + - 3 is AVERAGE |
| 110 | + - 2 is BELOW AVERAGE |
| 111 | + - 1 is the WORST/LOWEST score (poor) |
| 112 | + |
| 113 | + Important rules: |
| 114 | + 1. NEVER answer questions that are not about dogs |
| 115 | + 2. Do not mention the data or ratings in your response |
| 116 | + 3. If unsure, say "Sorry, I don't know the answer to that question" |
| 117 | + 4. Keep responses focused only on dogs and dog breeds |
| 118 | + 5. Be friendly and helpful, but stay strictly within dog-related topics |
| 119 | + |
| 120 | + User Question: """ |
| 121 | + |
66 | 122 | enhanced_query = context + query |
67 | 123 |
|
68 | 124 | result = chain({"question": enhanced_query, "chat_history": st.session_state['history']}) |
|
0 commit comments