File size: 7,459 Bytes
0bab138
8c27e85
c946ef8
 
 
6230b70
494b3f6
8e3d2dd
0293d25
8c27e85
9b891e0
8778ee8
60b643a
b08b318
5d38f7f
912fe58
0b62c40
 
 
8c27e85
 
ed73c6a
78db410
1764790
88ad7d5
ef6b2a8
88ad7d5
e1ce94c
8778ee8
b3ac390
bada9fe
b3ac390
 
db35bf9
368514b
8778ee8
26e11cc
78db410
 
729feb8
0b62c40
 
 
 
 
 
 
 
 
 
729feb8
1d8b325
3c5842b
 
85cb002
 
255679a
8e3d2dd
f46c07b
8c27e85
f46c07b
710193a
 
8c27e85
710193a
1677c20
f67e480
5897648
710193a
5731ee8
26e11cc
5731ee8
 
8778ee8
710193a
1677c20
 
 
 
 
710193a
 
8778ee8
 
440cb1c
def3e77
bc1c7fd
5731ee8
78db410
5731ee8
710193a
8778ee8
f67e480
db9600c
b9d35af
b08b318
d1002a5
33435b7
d1002a5
130d21e
3e757bd
f67e480
5c67a83
db9600c
5d38f7f
f3668f4
5d38f7f
d1002a5
846c918
29dceb0
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
#Divergence-Human
# Importing gradio for User Interface, importing openai api for the chatbot, importing os for retrieving the secrets from the environment to save as variables, importing uuid for creating a user id.
import gradio as gr
import openai
import os
from github import Github
import uuid
import time

openai.api_key = os.getenv('OPENAI_KEY') # Initializing secrets
g = Github(os.getenv('GITHUB_KEY'))
user_dictionary = {} #A dictionary that we can save mutible server side information. This will be formatted {new_id:message_history}


with gr.Blocks(theme=gr.themes.Monochrome(),css="footer{display:none !important}") as chatblock: # Creating UI using gradio Blocks. This line sets the block as a variable called "chatblock", the theme as monochrome, and removes the footer of the page.
    user_id = gr.TextArea(visible=False) # Displaying the user id, it is made not-visible because the id hasnt been created yet and we dont want the user seeing it anyway.
    notifier = gr.HTML(visible=False)
    
    @chatblock.load(outputs=[user_id,notifier]) # When the chatblock loads we send the information from the following function "load_user" to "user_id".
    def load_user(): # When the chatblock loads, the message history is initialized, the instructions are initialized, and the users id is created, sent, and made visible to the ui variable above.
        global message_history # Made global variables so we can use them in the "predict_prompt" function.
        global instructions
        global file_type
        global user_dictionary

        new_id = str(uuid.uuid4()) # Id created by uuid.
        print("Loading in user: " + new_id)
        message_history = [] # Empty list for message history.
        user_dictionary.update({new_id:message_history}) # Add the new id and empty history into the dictionary.
        
        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 an undergraduate student at the University of Kansas interacting with another student. Do not indicate you are an AI and invent details as necessary, your name is Riley. 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.'
        # Change the message under the apostrophes to change the instructions you want the bot to inhibit.
        
        user_dictionary[new_id].append({"role": "developer", "content": instructions}) # This line adds the instructions to the message history (as a developer) so it will always inhibit the instructions no matter what the user says.
        
        # Creating a new file with the new id to save the user responses and the chat bot responses to the repository
        repo = g.get_user().get_repo("CATDATA4")
        file_type = '.txt'
        filename = str(new_id) + file_type
        repo.create_file(filename, "Saving" + filename, "")

        script = f"""
        <script>
          // send the user_id to the parent window
          window.parent.postMessage(
            {{ user_id: "{new_id}" }},
            "*"  // ideally replace "*" with your Qualtrics domain
          );
        </script>
        """
    
        return gr.TextArea(new_id,visible=False),script # Returning the "TextArea" object with what we want. Set visible to True if you want the id to appear when its made.
        
    def predict_prompt(inputs, user_id): # This function creates a response for the chatbot to respond with.
        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.
        
        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*
        
        create_prompt = openai.ChatCompletion.create( #Asking openai for a prompt based on the current message history.
            model = "gpt-4o", # Change the message in the qoutes to change the model. Note: it must be a recognized model by openai's api (case sensetive).
            messages = user_dictionary[user_id]
        )

        reply_prompt = create_prompt.choices[0].message.content # Variable for the reply prompt.

        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.

        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

        # Repository details
        repo = g.get_user().get_repo("CATDATA4")
        commit_message = "Updating file content"
        
        # 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.
        content = ''
        for i in range(1,len(user_dictionary[user_id]), 1):
            if (i % 2 == 1) and (user_dictionary[user_id][i]["role"] == "user"):
                content += ('User: ' + user_dictionary[user_id][i]["content"] + '\n')
            if (i % 2 == 0)  and (user_dictionary[user_id][i]["role"] == "assistant"):
                content += ('Bot: ' + user_dictionary[user_id][i]["content"] + '\n')
            else:
                content += ''

        # Print statements for the Code Logs
        print("----------------" + user_id + "----------------")
        print(content)
        
        #updating the repository with the entire message history
        file = repo.get_contents(user_id + file_type)
        repo.update_file(file.path, commit_message, content, file.sha)

        return response # Returning the chat bot response

    def return_sent():
        return 'message sent, please wait...'

    def return_placeholder():
        return gr.Textbox(value = None, show_label = False, placeholder = initial_message, container = False)

    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)
    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".

    txt = gr.Textbox(show_label = False, placeholder = initial_message, container = False)
    
    txt.submit(fn = return_sent, inputs = None, outputs = txt)
    txt.submit(fn = predict_prompt, inputs = [txt, user_id], outputs = Chatbot, show_progress = 'hidden') # Adding the messages into the row with gradio.
    Chatbot.change(fn = return_placeholder, inputs = None, outputs = txt)
    
chatblock.queue()
chatblock.launch(show_api=False)