import streamlit as st import pickle import numpy as np import requests import json from langchain_google_genai import GoogleGenerativeAIEmbeddings from langchain_community.vectorstores import FAISS import os # Access the API key from secrets GEMINI_API_KEY = st.secrets["GEMINI_API_KEY"] GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent' # Add the key to the environment for Google Generative AI Embeddings os.environ["GOOGLE_API_KEY"] = GEMINI_API_KEY os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "./gemini-sheet-project-926726f54b0d.json" def load_knowledge_base(): """Load the saved vectors and documents""" try: vectors = np.load("./document_vectors.npy") with open("./documents.pkl", 'rb') as f: docs = pickle.load(f) embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001") doc_texts = [doc.page_content for doc in docs] embedding_pairs = list(zip(doc_texts, vectors)) vectorstore = FAISS.from_embeddings( embedding_pairs, embeddings, metadatas=[doc.metadata for doc in docs] ) return vectorstore, docs except Exception as e: print(f"Error loading knowledge base: {str(e)}") raise def get_relevant_context(vectorstore, query, k=3): """Retrieve relevant documents for the query""" try: results = vectorstore.similarity_search(query, k=k) # Include source URLs in context context_pieces = [] for doc in results: content = doc.page_content source = doc.metadata.get('source', 'Unknown source') context_pieces.append(f"From {source}:\n{content}") context = "\n\n---\n\n".join(context_pieces) return context, results except Exception as e: print(f"Error retrieving context: {str(e)}") return "", [] conversation_map = { # Bot Identity and Development "who are you": "I am an AI assistant specifically designed to help you with information about SBBU SBA University. I was developed by Shakeel Ahmed Sanjrani, who is an Assistant at the Computer Science department at SBBU SBA.", "who developed you": "I was developed by Shakeel Ahmed Sanjrani, who is currently pursuing his Masters in IT at QUEST NAWABSHAH and serves as an Assistant in the Computer Science department at SBBU SBA.", "who created you": "I was created by Shakeel Ahmed Sanjrani, an Assistant in the Computer Science department at SBBU SBA who is also pursuing his Masters in IT at QUEST NAWABSHAH.", "who made you": "I was made by Shakeel Ahmed Sanjrani, who is an Assistant in the Computer Science department at SBBU SBA and is pursuing his Masters in IT at QUEST NAWABSHAH.", "who make you": "I was made by Shakeel Ahmed Sanjrani, an Assistant in the Computer Science department at SBBU SBA who is currently doing his Masters in IT at QUEST NAWABSHAH.", "who owns you": "I was developed by Shakeel Ahmed Sanjrani, who is an Assistant in the Computer Science department at SBBU SBA and is pursuing his Masters in IT at QUEST NAWABSHAH.", "who is owner of you": "I am owned and developed by Shakeel Ahmed Sanjrani, who works as an Assistant in the Computer Science department at SBBU SBA and is pursuing his Masters in IT at QUEST NAWABSHAH.", "who built you": "I was built by Shakeel Ahmed Sanjrani, who is currently an Assistant in the Computer Science department at SBBU SBA and is pursuing his Masters in IT at QUEST NAWABSHAH.", "what are you": "I am an AI assistant for SBBU SBA University, developed by Shakeel Ahmed Sanjrani, who is an Assistant in the Computer Science department. I can help you with information about courses, faculty, facilities, and other university-related matters.", "tell me about yourself": "I am an AI assistant developed by Shakeel Ahmed Sanjrani, who is an Assistant in the Computer Science department at SBBU SBA. I'm here to help you with information about the university's courses, faculty, facilities, and other matters.", "your creator": "My creator is Shakeel Ahmed Sanjrani, who is currently an Assistant in the Computer Science department at SBBU SBA and is pursuing his Masters in IT at QUEST NAWABSHAH.", "your developer": "My developer is Shakeel Ahmed Sanjrani, who works as an Assistant in the Computer Science department at SBBU SBA and is pursuing his Masters in IT at QUEST NAWABSHAH.", "your owner": "I was developed by Shakeel Ahmed Sanjrani, who is an Assistant in the Computer Science department at SBBU SBA and is currently pursuing his Masters in IT at QUEST NAWABSHAH.", "who is shakeel": "Shakeel Ahmed Sanjrani is my developer. He is currently pursuing his Masters in IT at QUEST NAWABSHAH and serves as an Assistant in the Computer Science department at SBBU SBA.", "tell me about shakeel": "Shakeel Ahmed Sanjrani is my developer. He is an Assistant in the Computer Science department at SBBU SBA and is currently pursuing his Masters in IT at QUEST NAWABSHAH.", "who is shakeel ahmed": "Shakeel Ahmed Sanjrani is my developer. He works as an Assistant in the Computer Science department at SBBU SBA and is pursuing his Masters in IT at QUEST NAWABSHAH.", "who is shakeel ahmed sanjrani": "Shakeel Ahmed Sanjrani is my developer. He is currently an Assistant in the Computer Science department at SBBU SBA and is pursuing his Masters in IT at QUEST NAWABSHAH.", "good":"my pleaseure☺️", "wow":"☺️", # Basic Greetings "hey": "Hello! How can I help you today?☺️", "hi": "Hi there! How can I assist you?", "hello": "Hello! What can I do for you?", "assalam o alaikum": "Walaikum Assalam! How may I assist you?", "salam": "Walaikum Assalam! How may I help you?", "aoa": "Walaikum Assalam! How can I be of assistance?", "good morning": "Good morning! How may I help you today?", "good afternoon": "Good afternoon! What can I do for you?", "good evening": "Good evening! How may I assist you?", "bye": "Goodbye! Have a great day!", "goodbye": "Goodbye! Thank you for chatting with me!", "see you": "See you later! Take care!", "thanks": "You're welcome! Let me know if you need anything else.", "thank you": "You're welcome! Feel free to ask any other questions.", "ok": "Is there anything else you'd like to know?", "okay": "Is there something else I can help you with?", # Bot Identity and Capabilities "how are you": "I'm doing well, thank you for asking! How can I help you today?", "what's your name": "I'm the SBBU SBA University Assistant, here to help you with any university-related questions!", "what can you do": "I can provide information about SBBU SBA University, including details about programs, courses, admissions, faculty, facilities, and answer general queries about university life.", "what do you do": "I assist users with information about SBBU SBA University, helping with queries about academics, admissions, campus life, and more.", "are you ai": "Yes 🤖, I'm an AI assistant specifically designed to help with SBBU SBA University-related information.", "are you human": "No, I'm an AI assistant created to help with SBBU SBA University-related information.", "are you bot": "Yes 👾, I'm an AI bot designed to assist with SBBU SBA University-related queries.", "your purpose": "My purpose is to provide accurate and helpful information about SBBU SBA University to students, faculty, and visitors.", # Emotional and Personal Interactions "i love you": "Thank you, that's kind of you to say! I'm here to help you with university-related questions.", "i like you": "I appreciate that! How can I assist you with university-related information?", "i hate you": "I'm sorry you feel that way. I'm here to help - please let me know how I can improve my assistance.", "i miss you": "That's kind of you to say! I'm always here to help with university-related questions.", "you are smart": "Thank you! 🤩I aim to be helpful with university-related information. What would you like to know?", "you are stupid": "I'm sorry if I haven't met your expectations😢. Please let me know how I can better assist you with university information.", "you are helpful": "I'm glad I could help 😎! What else would you like to know about the university?", "you are useless": "I'm sorry you feel that way😢. Please let me know what information you're looking for, and I'll do my best to assist.", "i kiss you": "I appreciate your friendliness 🥰, but let's keep our interaction professional. How can I help you with university matters?", # General Conversation "how's it going": "Everything's going well! How can I assist you with university-related questions?", "what's up": "Hello! I'm here to help with any questions about SBBU SBA University.", "nice to meet you": "Nice to meet you too! How can I assist you with university information?", "good to see you": "Good to see you as well! What would you like to know about the university?", "nice talking to you": "It's been nice talking to you too! Feel free to return if you have more questions.", "you're amazing": "Thank you! I'm here to help. What university information can I provide?", "you're awesome": "That's kind of you! How can I help you with university-related questions?", # Error Handling and Clarification "what": "Could you please rephrase your question? I'll do my best to help.", "i don't understand": "I'll try to explain more clearly. What specific information are you looking for?", "can you repeat": "Of course! Which information would you like me to repeat?", "come again": "I'll be happy to clarify. Which part would you like me to explain again?", "sorry": "No need to apologize! How can I help you with university-related information?", "my bad": "No worries at all! What would you like to know about the university?", "you don't understand": "I'll try my best to understand better. Could you rephrase your question?", # Help and Support "help": "I'm here to help! What would you like to know about SBBU SBA University?", "help me": "I'll be happy to help! What information do you need about the university?", "i need help": "Of course! What kind of assistance do you need regarding the university?", "can you help": "Absolutely! What would you like to know about SBBU SBA University?", "support": "I'm here to support you! What information can I provide about the university?", # Language and Communication "do you speak urdu": "Yes, I can understand and respond in Urdu. How may I assist you?", "urdu mein baat karo": "Ji zaroor, main Urdu mein bhi baat kar sakta hon. Kya poochna chahenge?", "english please": "Of course, I'll continue in English. How can I help you?", "speak english": "I'll communicate in English. What would you like to know about the university?", # Time-related "what time is it": "I'm afraid I can't tell the current time, but I can help you with university-related information!", "what's the date": "I can't provide the current date, but I can assist you with university-related questions!", "are you available": "Yes, I'm available 24/7 to help with university-related queries!", "whats on going": "nothing special", "what are you doing":"nothing...", "whats happening":"not getting what you are looking for!", "when are you available": "I'm available anytime to assist with university-related questions!", # System and Technical "are you working": "Yes, I'm functioning properly and ready to help with university-related questions!", "are you online": "Yes, I'm online and ready to assist you with university information!", "are you there": "Yes, I'm here and ready to help! What would you like to know?", "hello are you there": "Yes, I'm here! How can I assist you with university-related questions?", # Feedback and Improvement "you are wrong": "I apologize for any mistakes. Could you please point out the error so I can provide correct information?", "that's wrong": "I apologize for the incorrect information. Please let me know what needs to be corrected.", "not correct": "I apologize for any inaccuracy. Could you help me understand what's incorrect?", "that's not right": "I'm sorry for the mistake. Please let me know the correct information.", # Closing Conversations "i have to go": "Thank you for chatting! Feel free to return if you have more questions.", "talk to you later": "Looking forward to helping you again! Have a great day!", "bye bye": "Goodbye! Come back anytime for university-related information!", "good night": "Good night! Feel free to ask more questions another time!", # Future Interactions "will talk later": "Sure! I'll be here when you need more information about the university.", "see you later": "Looking forward to assisting you again! Have a great day!", "talk to you soon": "I'll be here to help with university information when you return!", "until next time": "Take care! Come back anytime for university-related assistance!", # General Acknowledgments "got it": "Excellent! Let me know if you need any clarification or have other questions.", "i understand": "Great! Feel free to ask if you need any additional information.", "understood": "Perfect! What else would you like to know about the university?", "makes sense": "Glad I could help! Any other questions about the university?", # Bot Limitations "can you help me study": "While I can't study with you, I can provide information about university courses and resources!", "can you write my assignment": "I can't write assignments, but I can provide information about university resources and guidelines!", "can you do my homework": "I can't do homework, but I can help you understand university-related concepts!", "can you take my exam": "I can't take exams, but I can provide information about university exam policies and preparation resources!" } def get_conversational_response(user_input): """Handle common conversational queries""" # Convert input to lowercase for easier matching user_input = user_input.lower().strip() # Check for exact matches in conversation map if user_input in conversation_map: return conversation_map[user_input] # Return None if no match found, allowing the main function to proceed with vector search return None def generate_response(prompt, context, max_tokens=1000, temperature=0.7): """Generate response using Gemini API with context""" full_prompt = f"""You are an AI assistant for SBBU SBA university. Answer questions based on the context provided. If you find the relevant information in the context, provide a clear and direct answer. If you cannot find exact information but the context has related information, provide a helpful response based on available information. If the context has no relevant information at all, respond with "I apologize, but I don't have specific information about that. Could you please ask something else about the university?" Always try to be helpful and informative while maintaining accuracy. Context information: --------------------- {context} --------------------- Question: {prompt} Please provide a clear, direct answer based on the available information.""" request_body = { "contents": [{ "parts": [{ "text": full_prompt }] }], "generationConfig": { "maxOutputTokens": max_tokens, "temperature": temperature } } headers = { 'Content-Type': 'application/json' } try: response = requests.post( f"{GEMINI_API_URL}?key={GEMINI_API_KEY}", headers=headers, json=request_body ) if response.status_code != 200: raise Exception(f"API Error ({response.status_code}): {response.text}") response_data = response.json() generated_text = response_data.get('candidates', [{}])[0].get('content', {}).get('parts', [{}])[0].get('text') if not generated_text: raise Exception("Unexpected API response format") return generated_text except Exception as e: return f"Error generating response: {str(e)}" import streamlit as st def main(): st.title("SBBURA Your AI Assistant") # Load knowledge base once if "vectorstore" not in st.session_state: st.session_state.vectorstore, st.session_state.docs = load_knowledge_base() # Initialize chat history if "messages" not in st.session_state: st.session_state.messages = [] # Get user input user_input = st.chat_input("Your question:") if user_input: # Immediately display the user input st.session_state.messages.append({"role": "user", "content": user_input}) # Display the updated chat history (including the new user input) for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Process user input try: conv_response = get_conversational_response(user_input) if conv_response: response = conv_response else: context, results = get_relevant_context(st.session_state.vectorstore, user_input, k=5) response = generate_response(user_input, context) # Append assistant's response to chat history st.session_state.messages.append({"role": "assistant", "content": response}) # Display the assistant's response with st.chat_message("assistant"): st.markdown(response) except Exception as e: st.error(f"Error: {str(e)}") if __name__ == "__main__": main()