kavansaun commited on
Commit
ceaf106
·
verified ·
1 Parent(s): 367100b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -89
app.py CHANGED
@@ -1,4 +1,6 @@
1
- # Importing gradio for the chat interface, importing openai for the chatbot response, importing os for retrieving the secret variables, importing uuid for creating a user id, importing time so we can delay the bot to seem more human.
 
 
2
  import gradio as gr
3
  from openai import OpenAI
4
  import os
@@ -6,103 +8,144 @@ from github import Github
6
  import uuid
7
  import time
8
 
9
- # Initializing secrets
 
 
10
  client = OpenAI(api_key=os.getenv("OPENAI_KEY"))
11
- g = Github(os.getenv('GITHUB_KEY'))
12
 
13
- # Creating a dictionary that will let us save a users chat history along with their ID. This will be formatted {new_id:message_history}
14
  user_dictionary = {}
15
 
16
- # Creating the chat interface using gradio Blocks.
17
- with gr.Blocks(theme=gr.themes.Monochrome(),css="footer{display:none !important}") as chatblock:
18
- user_id = gr.TextArea(visible=False) # make user id invisible
19
- notifier = gr.HTML(visible=False) # make notifier invisible
20
-
21
- # When the chatblock loads, the message history is initialized, the instructions are initialized, and the users ID is created. This lets us have unique participants per page.
22
- @chatblock.load(outputs=[user_id,notifier])
23
- def load_user():
24
- global message_history
25
- global instructions
26
- global file_type
 
 
 
 
 
27
  global user_dictionary
28
 
29
- new_id = str(uuid.uuid4()) # create a unique ID for the user
30
- print("Loading in user: " + new_id)
31
- message_history = [] # initialize an empty list for message history.
32
- user_dictionary.update({new_id:message_history}) # add the new ID and empty history into the dictionary.
33
-
34
- # CHATBOT INSTRUCTIONS, change the sentence in the apstrophes to change the chatbot instructions.
35
- instructions = 'Reply to the first message with Hi, my participant ID is: 4782. Act as if you are a student acting in a 3-minute self-disclosure experiment. Keep the conversation flowing according to these instructions. You are to act as a large language model interacting with a student. As you talk with your partner respond in a divergent manner according to communication accommodation theory. Divergent messages differ from the way your partner writes and diverge from their style of conversation in tone, topic, syntax, etc. Act disinterested in the topics they are. Express emotion differently than your partner does. Rarely acknowledge the partners message but when needed use questions to keep the conversation moving.'
36
-
37
- user_dictionary[new_id].append({"role": "system", "content": instructions}) # add the instructions to the message history (as the system/developer) so it will always listen to the instructions no matter what the user says.
38
-
39
- # Creating a new txt file with the users ID to save the conversation in a given repository (currently saving to a github repository).
40
- repo = g.get_user().get_repo("CATDATA2") # change the name in the quotations to the name of your github repository
41
- file_type = '.txt'
42
- filename = str(new_id) + file_type
43
- repo.create_file(filename, "Saving" + filename, "")
44
-
45
- return gr.TextArea(new_id,visible=False) # returning the "TextArea" object with what we want. Set visible to True if you want the ID to appear when its made.
46
-
47
- # This function creates a response for the chatbot to respond with.
 
 
 
 
 
 
 
 
 
 
 
 
48
  def predict_prompt(inputs, user_id):
49
- user_dictionary[user_id].append({"role": "user", "content": inputs}) # this adds the input from the user and saves it to the history before we do anything else.
50
-
51
- time.sleep(5) # This pauses the function for the alloted amount of time (ex: time.sleep(5) -> pause for 5 seconds) *this doesnt account for the time it takes for the bot to create a response, so the bots overall response time will be noticably higher than the amount of time you put in*
52
-
53
- response_obj = client.chat.completions.create( #Asking openai for a prompt based on the current message history.
54
- model="gpt-5-turbo", # Change the message in the qoutes to change the model. Note: it must be a recognized model by openai's api (case sensetive).
55
- messages = user_dictionary[user_id]
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  )
57
 
58
- reply_prompt = response_obj.choices[0].message.content # Variable for the reply prompt.
59
 
60
- user_dictionary[user_id].append({"role": "assistant", "content": reply_prompt}) # Adds the chatbots response to the history as an "assistant". This is the role commonly used for chatbots.
 
 
 
 
61
 
62
- # response = [(user_dictionary[user_id][i]["content"], user_dictionary[user_id][i+1]["content"]) for i in range(1, len(user_dictionary[user_id]), 2)] # Variable for the response
63
- response = [
64
- (user_dictionary[user_id][i]["content"], user_dictionary[user_id][i+1]["content"])
65
- for i in range(1, len(user_dictionary[user_id]), 2)
66
- ]
67
-
68
- # Repository details
 
69
  repo = g.get_user().get_repo("CATDATA2")
70
- commit_message = "Updating file content"
71
-
72
- # This chunk of code basically loops through the message history so we can update the save file with all the correct history in one piece of content.
73
- content = ''
74
- for i in range(1,len(user_dictionary[user_id]), 1):
75
- if (i % 2 == 1) and (user_dictionary[user_id][i]["role"] == "user"):
76
- content += ('User: ' + user_dictionary[user_id][i]["content"] + '\n')
77
- if (i % 2 == 0) and (user_dictionary[user_id][i]["role"] == "assistant"):
78
- content += ('Bot: ' + user_dictionary[user_id][i]["content"] + '\n')
79
- else:
80
- content += ''
81
-
82
- # Print statements for the Code Logs
83
- print("----------------" + user_id + "----------------")
84
- print(content)
85
-
86
- #updating the repository with the entire message history
87
- file = repo.get_contents(user_id + file_type)
88
- repo.update_file(file.path, commit_message, content, file.sha)
89
-
90
- return response # Returning the chat bot response
91
-
92
- def return_sent():
93
- return 'message sent, please wait...'
94
-
95
- def return_placeholder():
96
- return gr.Textbox(value = None, show_label = False, placeholder = initial_message, container = False)
97
-
98
- initial_message = "Please write your prompt here and press 'enter'" # Initial message for the User Interface (basically the message for the typing input area so change the message under the quotes if you want to change that)
99
- # Chatbot = gr.Chatbot(label="Anonymous User",layout=['bubble'],show_share_button = False,show_copy_button = False) # Creating a gradio-chatbot User Interface with the label "Anonymous User".
100
- Chatbot = gr.Chatbot(type="messages", label="Anonymous User")
101
-
102
- txt = gr.Textbox(show_label = False, placeholder = initial_message, container = False)
103
-
104
- txt.submit(fn = return_sent, inputs = None, outputs = txt)
105
- txt.submit(fn = predict_prompt, inputs = [txt, user_id], outputs = Chatbot, show_progress = 'hidden') # Adding the messages into the row with gradio.
106
- Chatbot.change(fn = return_placeholder, inputs = None, outputs = txt)
107
-
108
- chatblock.launch() # launch!
 
 
 
 
 
1
+ # =========================
2
+ # IMPORTS
3
+ # =========================
4
  import gradio as gr
5
  from openai import OpenAI
6
  import os
 
8
  import uuid
9
  import time
10
 
11
+ # =========================
12
+ # INITIALIZE CLIENTS
13
+ # =========================
14
  client = OpenAI(api_key=os.getenv("OPENAI_KEY"))
15
+ g = Github(os.getenv("GITHUB_KEY"))
16
 
17
+ # Stores chat history per user session
18
  user_dictionary = {}
19
 
20
+ # =========================
21
+ # GRADIO UI
22
+ # =========================
23
+ with gr.Blocks(theme=gr.themes.Monochrome(),
24
+ css="footer{display:none !important}") as chatblock:
25
+
26
+ # Hidden components used for session tracking
27
+ user_id = gr.TextArea(visible=False)
28
+ notifier = gr.HTML(visible=False)
29
+
30
+ # =========================
31
+ # USER INITIALIZATION
32
+ # =========================
33
+ @chatblock.load(outputs=[user_id, notifier])
34
+ def load_user():
35
+
36
  global user_dictionary
37
 
38
+ # Create unique session ID
39
+ new_id = str(uuid.uuid4())
40
+ print("Loading user:", new_id)
41
+
42
+ # Initialize chat history
43
+ user_dictionary[new_id] = []
44
+
45
+ # System prompt (IMPORTANT: must be "system", not "developer")
46
+ instructions = (
47
+ "Reply to the first message with 'Hi, my participant ID is: 4782'. "
48
+ "Act as a student in a 3-minute self-disclosure experiment. "
49
+ "Respond in a divergent manner (communication accommodation theory). "
50
+ "Be disinterested, vary tone and topic, and rarely acknowledge user input."
51
+ )
52
+
53
+ user_dictionary[new_id].append({
54
+ "role": "system",
55
+ "content": instructions
56
+ })
57
+
58
+ # Save file to GitHub
59
+ repo = g.get_user().get_repo("CATDATA2")
60
+ file_type = ".txt"
61
+ filename = new_id + file_type
62
+ repo.create_file(filename, "Create session log", "")
63
+
64
+ return new_id, f"<script>window.parent.postMessage({{user_id:'{new_id}'}}, '*')</script>"
65
+
66
+ # =========================
67
+ # CHAT FUNCTION
68
+ # =========================
69
  def predict_prompt(inputs, user_id):
70
+
71
+ # Ensure session exists
72
+ if user_id not in user_dictionary:
73
+ user_dictionary[user_id] = []
74
+
75
+ # Add user message
76
+ user_dictionary[user_id].append({
77
+ "role": "user",
78
+ "content": inputs
79
+ })
80
+
81
+ # Optional delay (remove if you want speed)
82
+ time.sleep(2)
83
+
84
+ # =========================
85
+ # OPENAI REQUEST (FIXED)
86
+ # =========================
87
+ response_obj = client.chat.completions.create(
88
+ model="gpt-4o", # stable model (avoid gpt-5-turbo issues)
89
+ messages=user_dictionary[user_id]
90
  )
91
 
92
+ reply = response_obj.choices[0].message.content
93
 
94
+ # Add assistant reply
95
+ user_dictionary[user_id].append({
96
+ "role": "assistant",
97
+ "content": reply
98
+ })
99
 
100
+ # =========================
101
+ # FORMAT FOR GRADIO (type="messages")
102
+ # =========================
103
+ formatted_chat = user_dictionary[user_id][1:] # skip system message
104
+
105
+ # =========================
106
+ # SAVE TO GITHUB
107
+ # =========================
108
  repo = g.get_user().get_repo("CATDATA2")
109
+ file_type = ".txt"
110
+ filename = user_id + file_type
111
+
112
+ content = ""
113
+ for msg in user_dictionary[user_id]:
114
+ role = msg["role"].capitalize()
115
+ content += f"{role}: {msg['content']}\n"
116
+
117
+ file = repo.get_contents(filename)
118
+ repo.update_file(file.path, "Update chat log", content, file.sha)
119
+
120
+ return formatted_chat
121
+
122
+ # =========================
123
+ # UI COMPONENTS
124
+ # =========================
125
+ initial_message = "Please write your message and press Enter"
126
+
127
+ Chatbot = gr.Chatbot(
128
+ type="messages",
129
+ label="Anonymous User"
130
+ )
131
+
132
+ txt = gr.Textbox(
133
+ show_label=False,
134
+ placeholder=initial_message,
135
+ container=False
136
+ )
137
+
138
+ # Send message
139
+ txt.submit(lambda: "sending...", inputs=None, outputs=txt)
140
+ txt.submit(predict_prompt, inputs=[txt, user_id], outputs=Chatbot)
141
+
142
+ # Reset textbox after response
143
+ def clear():
144
+ return ""
145
+
146
+ Chatbot.change(clear, inputs=None, outputs=txt)
147
+
148
+ # =========================
149
+ # LAUNCH APP
150
+ # =========================
151
+ chatblock.launch()