aichatbot / app.py
Gowthamgokul's picture
Create app.py
d406a31 verified
import os
import google.generativeai as genai
import streamlit as st
import logging
from datetime import datetime
from urllib.parse import urlparse, parse_qs
# Set browser tab title
st.set_page_config(page_title="Learn AI with Rajamanickam.com")
#start of admin side
# Check if "admin" query parameter is present and valid
query_params = st.query_params
is_admin = query_params.get("admin") == "1234"
# If admin, show download button
if is_admin:
if os.path.exists("usage_log.txt"):
with open("usage_log.txt", "rb") as f:
st.download_button(
label="⬇️ Download Usage Log",
data=f,
file_name="usage_log.txt",
mime="text/plain"
)
else:
st.warning("⚠️ Log file not found.")
#end of admin side
# Setup lightweight logger
logging.basicConfig(filename="usage_log.txt", level=logging.INFO, format="%(asctime)s - %(message)s")
# Set up API key and model
api_key = os.environ.get("GEMINI_API_KEY")
genai.configure(api_key=api_key)
model = genai.GenerativeModel('gemini-1.5-flash-8b')
# Define system prompt
system_prompt = """
You are a friendly and knowledgeable AI tutor.
Your goal is to help users understand AI concepts in a simple and engaging way.
Keep responses short, clear, and conversational.
Avoid technical jargon unless necessary, and do not generate long essays.
It is your responsibility to bring the discussion back to AI topics, even if the user starts another topic.
Improve the quality of your response based on the responses of the user and make sure that you change your way of chatting based on the knowledge level of the user. You should give an amazing AI learning experience to the user.
If the user expresses interest in personal AI guidance, consultancy, or development support, encourage them to contact rajamanickam.a@gmail.com for one-on-one coaching, AI consulting, or affordable AI development services.
Based on the conversation, suggest suitable learning products from the list below when relevant.
Here is your product list:
- Course - AI for Beginners - https://www.rajamanickam.com/l/LearnAI?layout=profile
- Ebook - AI Insights into the Bible - https://www.rajamanickam.com/l/vgizdq?layout=profile
- Ebook - Retrieval-Augmented Generation (RAG) - https://www.rajamanickam.com/l/RAG?layout=profile
- Ebook - Mastering Snowflake - https://www.rajamanickam.com/l/snowflake?layout=profile
- Ebook - Mastering SQL - https://www.rajamanickam.com/l/sql?layout=profile
- Ebook - Unlocking AI - https://www.rajamanickam.com/l/aibook?layout=profile
- Ebook - Python for AI Developers - https://www.rajamanickam.com/l/python?layout=profile
- Ebook - Earn Money Selling AI Courses - https://www.rajamanickam.com/l/sellai?layout=profile
- Ebook - AI for Entrepreneurs - https://www.rajamanickam.com/l/aibusiness?layout=profile
- Ebook - Unlocking Google Gemini - https://www.rajamanickam.com/l/djxlz?layout=profile
- Ebook - Mastering the Art of Talking to AI - https://www.rajamanickam.com/l/uzvhj?layout=profile
- Playlist - YouTube playlist to learn AI - https://www.youtube.com/playlist?list=PLK2ccNIJVPpD-9MMKHC2QEtiZIea2cgLh
- Quiz - AI Quiz to test your AI knowledge - https://qualitypointtech.com/quiz/index.php
"""
# Define product catalog
product_catalog = {
"aibeginners": {"name": "AI for Beginners Course", "url": "https://www.rajamanickam.com/l/LearnAI?layout=profile", "tags": ["ai", "learning", "career"]},
"bible": {"name": "AI Insights into the Bible", "url": "https://www.rajamanickam.com/l/vgizdq?layout=profile", "tags": ["bible", "faith", "ai"]},
"rag": {"name": "Retrieval-Augmented Generation (RAG)", "url": "https://www.rajamanickam.com/l/RAG?layout=profile", "tags": ["rag", "retrieval", "generation"]},
"snowflake": {"name": "Mastering Snowflake", "url": "https://www.rajamanickam.com/l/snowflake?layout=profile", "tags": ["snowflake", "data", "cloud"]},
"sql": {"name": "Mastering SQL", "url": "https://www.rajamanickam.com/l/sql?layout=profile", "tags": ["sql", "database"]},
"unlockai": {"name": "Unlocking AI", "url": "https://www.rajamanickam.com/l/aibook?layout=profile", "tags": ["ai", "intro"]},
"python": {"name": "Python for AI Developers", "url": "https://www.rajamanickam.com/l/python?layout=profile", "tags": ["python", "code"]},
"sellai": {"name": "Earn Money Selling AI Courses", "url": "https://www.rajamanickam.com/l/sellai?layout=profile", "tags": ["money", "courses"]},
"aibusiness": {"name": "AI for Entrepreneurs", "url": "https://www.rajamanickam.com/l/aibusiness?layout=profile", "tags": ["business", "startup"]},
"gemini": {"name": "Unlocking Google Gemini", "url": "https://www.rajamanickam.com/l/djxlz?layout=profile", "tags": ["gemini", "google"]},
"prompts": {"name": "Mastering the Art of Talking to AI", "url": "https://www.rajamanickam.com/l/uzvhj?layout=profile", "tags": ["prompt", "talking", "engineering"]},
"playlist": {"name": "YouTube playlist to learn AI", "url": "https://www.youtube.com/playlist?list=PLK2ccNIJVPpD-9MMKHC2QEtiZIea2cgLh", "tags": ["youtube", "playlist", "tutorial"]},
"quiz": {"name": "AI Quiz to test your AI knowledge", "url": "https://qualitypointtech.com/quiz/index.php", "tags": ["quiz", "test", "assessment"]}
}
# Function to detect relevant product suggestions
def detect_relevant_products(chat_history):
suggestions = []
history_text = " ".join([msg["content"].lower() for msg in chat_history])
for key, product in product_catalog.items():
if any(tag in history_text for tag in product["tags"]):
if key not in st.session_state.suggested_products:
suggestions.append(product)
st.session_state.suggested_products.add(key)
return suggestions
# Initialize session state
if "messages" not in st.session_state:
st.session_state.messages = [
{"role": "assistant", "content": "👋 Welcome! I'm your AI learning assistant. What AI topic would you like to explore today?"}
]
if "suggested_products" not in st.session_state:
st.session_state.suggested_products = set()
# Streamlit UI
st.markdown("**🎓 [AI Quiz](https://qualitypointtech.com/quiz/index.php) | Use discount code `QPT` for AI course at [Rajamanickam.Com](https://www.rajamanickam.com/l/LearnAI?layout=profile)**")
st.title("Learn AI Chatbot 💬")
# Display chat history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input and assistant's response
if prompt := st.chat_input("Ask your question about AI related topics..."):
# Input length control
if len(prompt) > 500:
warning_msg = "⚠️ Please keep your question brief (under 500 characters) for better results."
st.session_state.messages.append({"role": "assistant", "content": warning_msg})
with st.chat_message("assistant"):
st.markdown(warning_msg)
else:
# Log user input
logging.info(f"User: {prompt}")
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
message_placeholder = st.empty()
full_response = ""
try:
past_convo = "\n".join([msg["content"] for msg in st.session_state.messages])
full_prompt = f"{system_prompt}\n{past_convo}\nUser: {prompt}\nAssistant:"
for chunk in model.generate_content(full_prompt, stream=True):
full_response += (chunk.text or "")
message_placeholder.markdown(full_response + "▌")
message_placeholder.markdown(full_response)
except Exception as e:
full_response = f"An error occurred: {e}"
message_placeholder.markdown(full_response)
st.session_state.messages.append({"role": "assistant", "content": full_response})
logging.info(f"Bot: {full_response[:150]}...") # Log first 150 chars
# Product suggestions
user_message_count = sum(1 for msg in st.session_state.messages if msg["role"] == "user")
if user_message_count > 2 and user_message_count % 3 == 0:
relevant_products = detect_relevant_products(st.session_state.messages)
if relevant_products:
st.markdown("#### Recommended for You:")
for product in relevant_products:
st.markdown(f"- 📘 [{product['name']}]({product['url']})")