Spaces:
Build error
Build error
File size: 6,804 Bytes
424ff00 6585179 1787470 424ff00 f550e66 424ff00 0f65b9a 424ff00 f26a96e f550e66 424ff00 eeeab9f f550e66 0f65b9a ee65358 0f65b9a 5f0684c ee65358 0f65b9a 424ff00 9e15e50 424ff00 f550e66 714e8f2 117bf69 424ff00 f219828 424ff00 77e24b3 4912f30 98cc90f ce718d2 424ff00 e8a7dac 424ff00 0f65b9a ee65358 6dbc53c 6b86572 36dd46a 2411c1f 37161b9 c3effea 37161b9 fdc1e26 424ff00 0f65b9a 7fef507 0f65b9a 424ff00 0f65b9a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | 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.") |