Smart-Assistant / app.py
ale979's picture
Update app.py
117bf69 verified
Raw
History Blame Contribute Delete
6.8 kB
import gradio as gr
import os
import mysql.connector
from datetime import datetime
from langchain.chat_models import ChatOpenAI
from langchain.retrievers.document_compressors import LLMChainExtractor
from langchain.retrievers.multi_query import MultiQueryRetriever
from langchain.retrievers import ContextualCompressionRetriever
from langchain.prompts.chat import ChatPromptTemplate, HumanMessagePromptTemplate
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
chat = ChatOpenAI(model="gpt-4o-mini")
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
embedding_function = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY, model="text-embedding-3-large")
def track_user_interaction(user_input, action, user_id):
user_id = str(user_id)
print(user_id)
# Construct connection string
from mysql.connector import errorcode
try:
connection = mysql.connector.connect(user=os.getenv("MYSQLUSER"), password= os.getenv("MYSQLPASSWORD"), host=os.getenv("DBHOST"), port=3306, database="user_interact")
print("Connection established")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with the user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
cursor = connection.cursor()
# Create table if it doesn't exist
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_interactions (
user_input LONGTEXT NOT NULL,
action TEXT NOT NULL,
timestamp TEXT NOT NULL,
user_id TEXT NOT NULL
);
''')
# Prepare data
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
user_input_str = str(user_input)
action_str = str(action)
# Use a parameterized query to insert data
insert_query = """
INSERT INTO user_interactions (user_input, action, timestamp, user_id)
VALUES (%s, %s, %s, %s)
"""
cursor.execute(insert_query, (user_input_str, action_str, timestamp, user_id))
# Commit changes and close connection
connection.commit()
connection.close()
def profile_user(request: gr.Request):
query_params = dict(request.query_params)
try:
username = dict(request.query_params)["username"]
user_id = username
track_user_interaction("", "login", user_id)
#if dict(request.query_params)["password"] == os.getenv("APP_PASSWORD"):
# return user_id
#else:
return user_id
except:
return None
def answer_query(message, chat_history):
base_compressor = LLMChainExtractor.from_llm(chat)
db = Chroma(persist_directory = "./slide_chromaDB4", embedding_function=embedding_function, collection_name="slideCollection")
base_retriever = db.as_retriever(search_type="similarity_score_threshold",search_kwargs={'score_threshold': 0.2})
mq_retriever = MultiQueryRetriever.from_llm(retriever = base_retriever, llm=chat)
compression_retriever = ContextualCompressionRetriever(base_compressor=base_compressor, base_retriever=mq_retriever)
matched_docs = compression_retriever.get_relevant_documents(query = message)
print(matched_docs)
context = ""
for doc in matched_docs:
page_content = doc.page_content
context+=page_content
context += "\n\n"
template = """
You are an AI particularly skilled at captivating storytelling for educational purposes.
You know how tell a compelling, structure and exhaustive narrative around any given academic topic.
What you are particularly good at, is taking any given input and building a storyline. And outlining presentation slides.
Answer the following question by using the context given below in the triple backticks, do only use in exceptions any other information to answer the question.
If you can't answer the given question with the given context, you can say so.
Context: ```{context}```
----------------------------
Question: {query}
----------------------------
Answer: """
human_message_prompt = HumanMessagePromptTemplate.from_template(template=template)
chat_prompt = ChatPromptTemplate.from_messages([human_message_prompt])
prompt = chat_prompt.format_prompt(query = message, context = context)
response = chat(messages=prompt.to_messages()).content
chat_history.append((message,response))
print(context)
return "", chat_history
with gr.Blocks() as demo:
user_id = gr.Textbox(visible=False)
gr.HTML("<h1 align = 'center'>ChatGPT augmented with Cyber Security Knowledge</h1>")
with gr.Column():
gr.Markdown("""### The following steps can help you structure the assigned task for yourself.
**1. Define Your Workshop Objective.**
Choose a topic that is timely and fills a skill gap relevant to your consulting firm’s strategic goals.
Define learning goals that focus on acquiring skills applicable in real-world consulting scenarios.
Consider how mastering these skills can innovate and enhance your firm’s service offerings, aligning with emerging market needs and providing a competitive edge.
*The AI can help you to draft story points based on your input.*
**What are Story Points?**
Story points are key milestones in your presentation that underline important learning outcomes. You can adapt them in the next step to cover skills and insights crucial for your firm’s services.
**2. Content Requirements and Story Points.**
Develop content that supports your workshop’s learning goals, using theories, case studies, and real-world applications.
**3. Evaluating Story Points.**
Effective story points are clear, engaging, and directly tied to your objectives. They should advance understanding and skill acquisition.
""")
chatbot = gr.Chatbot()
msg = gr.Textbox(label = "Enter your question here")
msg.submit(answer_query,[msg,chatbot],[msg,chatbot]).then(track_user_interaction, inputs=[chatbot, gr.Textbox("promptanswerSimpleRAG", visible=False), user_id])
submitChat = gr.Button("Submit message")
submitChat.click(answer_query,[msg,chatbot],[msg,chatbot]).then(track_user_interaction, inputs=[chatbot, gr.Textbox("promptanswerSimpleRAG", visible=False), user_id])
demo.load(fn=profile_user, outputs = user_id)
if __name__ == "__main__":
demo.launch(show_api=False, auth_message = "Hello there! Please log in to access the NarrativeNet Weaver using your Prolific ID as username. Use the password supplied in Qualtrics.")