sam2ai commited on
Commit
374c0fd
·
1 Parent(s): 363527f

Synced repo using 'sync_with_huggingface' Github Action

Browse files
Roleplay/__pycache__/promptTemplate.cpython-311.pyc ADDED
Binary file (6.43 kB). View file
 
Roleplay/__pycache__/user_roles.cpython-311.pyc ADDED
Binary file (1.38 kB). View file
 
Roleplay/app.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from user_roles import user_role_list
3
+ from promptTemplate import task_generator
4
+ from promptTemplate import conversation_generator
5
+ import openai
6
+ import json
7
+
8
+
9
+
10
+ # page title
11
+ st.set_page_config(page_title="LLM Roleplay")
12
+
13
+ # sidebar content
14
+ with st.sidebar:
15
+ st.markdown("My side bar")
16
+
17
+ # main function
18
+ def main():
19
+ st.title("LLM Roleplay")
20
+
21
+ if "submit" not in st.session_state:
22
+ st.session_state.submit = False
23
+ if "submit2" not in st.session_state:
24
+ st.session_state.submit2 = False
25
+ if "initial" not in st.session_state:
26
+ st.session_state.initial = False
27
+ if "initial2" not in st.session_state:
28
+ st.session_state.initial2 = False
29
+ if "extracted" not in st.session_state:
30
+ st.session_state.extracted = False
31
+
32
+ with st.form(key="form"):
33
+ role1, role2 = st.columns([0.5, 0.5])
34
+
35
+ with role1:
36
+ # role selection dropdown menu
37
+ selected_roles_user = st.multiselect("Select User Roles", user_role_list)
38
+ user = ', '.join(selected_roles_user)
39
+ # user = st.text_input("User Role (EDIT ME)", value=', '.join(selected_roles_user))
40
+
41
+ with role2:
42
+ # role selection dropdown menu
43
+ selected_roles_assistant = st.multiselect("Select Assistant Roles", user_role_list)
44
+ assistant = ', '.join(selected_roles_assistant)
45
+ # assistant = st.text_input("Assistant Role (EDIT ME)", value=', '.join(selected_roles_assistant))
46
+
47
+ # input text for task
48
+ # task = st.text_input("Topic")
49
+
50
+ # input text for openAiKey
51
+ openAiKey = st.text_input(label="Input the openai key", type="password")
52
+
53
+ # form submit button and setting up the session_state
54
+ if st.form_submit_button(label="Submit"):
55
+ st.session_state.submit = True
56
+ st.session_state.initial = True
57
+ # print(user)
58
+ # print(assistant)
59
+ # print(prompt(user, assistant))
60
+
61
+ if st.session_state.submit:
62
+ print("Inside submit")
63
+ with st.spinner("In progress..."):
64
+ try:
65
+ if st.session_state.initial:
66
+ st.session_state["task"] = task_generator(user, assistant, openAiKey)
67
+ print("task_generator")
68
+ # print("\n\n\nAfter the task\n\n\n")
69
+ st.session_state.initial = False
70
+ with st.form(key="form2"):
71
+
72
+ # input text for task
73
+ st.session_state["task"] = st.text_input("The topic for the roleplay (Edit if required)", value=st.session_state["task"])
74
+
75
+ if st.form_submit_button(label="Generate"):
76
+ st.session_state.submit2 = True
77
+ # print(st.session_state["task"])
78
+ st.session_state.initial2 = True
79
+ # print("\n\nsubmit2 statues:")
80
+ # print(st.session_state.submit2)
81
+ # print("\n\n")
82
+ except Exception as err:
83
+ st.error(err)
84
+
85
+
86
+
87
+
88
+ if st.session_state.submit2:
89
+ print("Inside submit2")
90
+ st.session_state.extracted = False
91
+ with st.expander(label="role play"):
92
+ with st.spinner("Generating..."):
93
+ try:
94
+ if st.session_state.initial2:
95
+
96
+ roleplay, user_convo, assistant_convo = conversation_generator(user, assistant, st.session_state["task"])
97
+ # roleplay = {'user': 'Actor', 'assistant': 'Chef', 'task': "Planning and preparing healthy meals that meet the actor's strict dietary requirements.", 'conversations': [{'from': 'user', 'value': 'Create a list of movie genres that will inspire each course of the menu.'}, {'from': 'assistant', 'value': 'To create a list of movie genres that will inspire each course of the menu, we can consider a variety of genres that offer distinct flavors and themes. Here is a suggested list:\n\n1. Sci-Fi: Molecular Gastronomy Appetizer\n2. Romance: Elegant Seafood Entrée\n3. Action: Spicy Asian Fusion Main Course\n4. Comedy: Playful Dessert\n5. Western: Smoked BBQ Main Course'}, {'from': 'user', 'value': 'Choose a specific sci-fi movie that will inspire the molecular gastronomy appetizer.'}, {'from': 'assistant', 'value': 'To choose a specific sci-fi movie that will inspire the molecular gastronomy appetizer, we can look for a movie that showcases futuristic technology, innovative concepts, and unique visuals. One movie that fits this description is "Blade Runner." The dystopian setting and advanced technology in the movie can serve as inspiration for creating a visually stunning and futuristic molecular gastronomy appetizer.'}], 'specified_task': 'Chef will help Actor create a delectable five-course menu inspired by movie genres. From a sci-fi-inspired molecular gastronomy appetizer to a western-themed smoked BBQ main course, Chef will bring the flavors and ambiance of each genre to life, ensuring a memorable dining experience for Actor and their guests.', 'length': 4}
98
+ st.session_state["roleplay"] = roleplay
99
+ st.session_state.initial2 = False
100
+ print("conversation_generator")
101
+ # print("roleplay")
102
+ # print(roleplay)
103
+ # print("user_convo")
104
+ # print(user_convo)
105
+ # print("assistant_convo")
106
+ # print(assistant_convo)
107
+ st.session_state.extracted = True
108
+ except Exception as err:
109
+ st.error(err)
110
+
111
+ if st.session_state.extracted:
112
+ json_data = st.session_state["roleplay"]
113
+ json_string = json.dumps(json_data, ensure_ascii=False)
114
+ if st.download_button(label="Save as jsonl", data=json_string , mime="application/json"):
115
+ st.success("Successfully saved")
116
+
117
+ if st.button("Clear"):
118
+ st.session_state.submit = False
119
+ st.session_state.submit2 = False
120
+ st.session_state.initial = False
121
+ st.session_state.initial2 = False
122
+ st.session_state.extracted = False
123
+ if "task" in st.session_state:
124
+ del st.session_state["task"]
125
+ if "roleplay" in st.session_state:
126
+ del st.session_state["roleplay"]
127
+ st.experimental_rerun()
128
+
129
+
130
+ if __name__ == "__main__":
131
+ main()
Roleplay/promptTemplate.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import openai
2
+ import streamlit as st
3
+ from camel.agents import RolePlaying
4
+ from camel.utils import print_text_animated
5
+ from datetime import datetime
6
+
7
+
8
+
9
+ def task_generator(user,assistant, openAiKey):
10
+
11
+ openai.api_key = openAiKey
12
+
13
+ prompt = f'''User: Farmer, Assistant: Business analyst
14
+ Generate a conversation topic: Help the farmer in deciding the optimal choice for crops this year\n
15
+ User: Accountant, Assistant: Developer
16
+ Generate a conversation topic: Developing a custom accounting software to automate financial processes and reduce errors.\n
17
+ User: Athlete, Assistant: Doctor
18
+ Generate a conversation topic: Developing a personalized nutrition plan to optimize athletic performance and recovery.\n
19
+ User: Politician, Assistant: Social Media Manager\n
20
+ Generate a conversation topic: Develop a social media strategy to increase the politician's online presence and engagement with constituents.\n
21
+ User: {user}, Assistant: {assistant}
22
+ Generate a conversation topic:'''
23
+
24
+ response = openai.Completion.create(
25
+ engine="text-davinci-002", #Use gpt-3 engine.
26
+ prompt=prompt,
27
+ max_tokens=50,
28
+ n=1
29
+ )
30
+ task = response.choices[0].text.strip()
31
+
32
+ return task
33
+
34
+ def conversation_generator(user,assistant, task, chat_limit=2):
35
+ task_prompt = task
36
+ print(task)
37
+ print(user)
38
+ print(assistant)
39
+ role_play_session = RolePlaying(assistant, user, task_prompt)
40
+ # print(Fore.CYAN + f"Specified task prompt:\n{role_play_session.task_prompt}\n")
41
+ # print(f"Specified task prompt:\n{role_play_session.task_prompt}\n")
42
+
43
+ chat_turn_limit, n = chat_limit, 0
44
+ assistant_msg, _ = role_play_session.init_chat()
45
+
46
+ user_chat = []
47
+ assistant_chat = []
48
+ now = datetime.now()
49
+
50
+ current_time = now.strftime("%H:%M:%S")
51
+ print("Current Time =", current_time)
52
+
53
+ while n < chat_turn_limit:
54
+ n += 1
55
+ try:
56
+ (assistant_msg, _, _), (user_msg, _, _) = role_play_session.step(assistant_msg)
57
+ assert user_msg.content is not None
58
+ with st.chat_message("user"):
59
+ user_content = user_msg.content.replace("Instruction: ", "").replace("Input: None", "")
60
+ st.text(user_content)
61
+ assert assistant_msg.content is not None
62
+ with st.chat_message("assistant"):
63
+ assistant_content = assistant_msg.content.replace("Solution: ", "").replace("Next request.","")
64
+ st.text(assistant_content)
65
+
66
+ except:
67
+ break
68
+
69
+ # print(Fore.BLUE + f"AI User:\n\n{user_msg.content}\n\n")
70
+ # print(f"AI User:\n\n{user_msg.content}\n\n")
71
+ user_chat.append(user_msg.content)
72
+ if "Next request." not in assistant_msg.content:
73
+ break
74
+
75
+ # print(Fore.GREEN + f"AI Assistant:\n\n{assistant_msg.content}\n\n")
76
+ # print(f"AI Assistant:\n\n{assistant_msg.content}\n\n")
77
+ assistant_chat.append(assistant_msg.content)
78
+ if "<CAMEL_TASK_DONE>" in user_msg.content:
79
+ break
80
+
81
+ #Processing the generated conversation
82
+
83
+ final_user_convo = []
84
+ final_assistant_convo = []
85
+
86
+ if len(assistant_chat)==0 or len(user_chat)==0:
87
+ return "Empty list"
88
+
89
+
90
+ for i in range(len(user_chat)):
91
+
92
+ if ("Next request" in assistant_chat[i]) and ("Instruction:" in user_chat[i]) and ("Input:" in user_chat[i]):
93
+ final_instruction = ""
94
+ try:
95
+ instruction = user_chat[i].split("Instruction:")[1].split("Input:")[0]
96
+ input = user_chat[i].split("Input:")[1].strip()
97
+ except:
98
+ continue
99
+
100
+ if input.strip() == 'None':
101
+ final_instruction = final_instruction+instruction.replace("\n"," ")
102
+ final_instruction = final_instruction.strip()
103
+ else:
104
+ final_instruction = instruction.replace("\n"," ")+"\ninput:"+input #If an input is there, then add a newline after instruction, input: and then the input.
105
+ final_instruction = final_instruction.strip()
106
+
107
+ final_user_convo.append(final_instruction)
108
+ final_assistant_convo.append(assistant_chat[i].replace("Solution:","").replace("Next request.","").strip())
109
+
110
+ else:
111
+ break #Sometimes faulty chat gets generated. A proper convo has Next request at the end
112
+
113
+ assert (len(final_user_convo)-len(assistant_chat))<=1
114
+ # print('\n\n'+'End of the conversation\n\n')
115
+ # print("*"*150, end='\n')
116
+ final_convo_list = []
117
+
118
+ for i in range(len(final_user_convo)):
119
+ user_convo = {"from":"user","value":final_user_convo[i]}
120
+ assistant_convo = {"from":"assistant","value":final_assistant_convo[i]}
121
+ final_convo_list.append(user_convo)
122
+ final_convo_list.append(assistant_convo)
123
+
124
+ length = len(final_convo_list)
125
+
126
+ final_json_entry = {'user':user,'assistant':assistant,'task':task_prompt,'conversations':final_convo_list, 'specified_task':role_play_session.task_prompt, 'length':length}
127
+ # pprint.pprint(final_json_entry)
128
+ return final_json_entry, final_user_convo, final_assistant_convo
Roleplay/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ streamlit
2
+ openai
Roleplay/user_roles.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ user_role_list = ['AI Researcher', 'Accountant', 'Actor', 'Actress', 'Archaeologist', 'Archivist', 'Architect', 'Artist', 'Astronomer',
2
+ 'Athlete', 'Author', 'Barista', 'Bartender', 'Biologist', 'Biomedical Engineer', 'Blogger', 'CEO', 'Carpenter', 'Cartoonist',
3
+ 'Chef', 'Chauffeur', 'Counselor', 'Customer', 'DJ', 'Dancer', 'Data Analyst', 'Dentist', 'Designer', 'Director', 'Doctor', 'Electrician',
4
+ 'Engineer', 'Entrepreneur', 'Environmentalist', 'Ethical Hacker', 'Event Planner', 'Explorer', 'Farmer', 'Fashion Model', 'Financial Analyst',
5
+ 'Firefighter', 'Fitness Coach', 'Florist', 'Gamer', 'Geologist', 'Graphic Designer', 'Hair Stylist', 'Historian', 'Housekeeper', 'Illustrator',
6
+ 'Lawyer', 'Librarian', 'Magician', 'Magistrate', 'Makeup Artist', 'Manager', 'Mechanic', 'Meteorologist', 'Musician', 'News Reporter', 'Novelist',
7
+ 'Nurse', 'Nutritionist', 'Parent', 'Personal Trainer', 'Pharmacist', 'Philanthropist', 'Philosopher', 'Photographer', 'Pilot', 'Plumber', 'Poet',
8
+ 'Police Officer', 'Producer', 'Psychologist', 'Real Estate Agent', 'Receptionist', 'Researcher', 'Salesperson', 'Scientist', 'Superintendent', 'Security guard',
9
+ 'Social Media Influencer', 'Social Worker', 'Software Engineer', 'Sommelier', 'Student', 'Taxi Driver', 'Teacher', 'Therapist', 'Tour Guide', 'Translator',
10
+ 'Traveler', 'Veterinarian', 'Waiter', 'Web Developer', 'Wedding Planner', 'Writer', 'Yoga Instructor', 'Zoologist']