-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3256e6f
commit afd79c3
Showing
6 changed files
with
271 additions
and
0 deletions.
There are no files selected for viewing
Binary file not shown.
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
import streamlit as st | ||
from user_roles import user_role_list | ||
from promptTemplate import task_generator | ||
from promptTemplate import conversation_generator | ||
import openai | ||
import json | ||
|
||
|
||
|
||
# page title | ||
st.set_page_config(page_title="LLM Roleplay") | ||
|
||
# sidebar content | ||
with st.sidebar: | ||
st.markdown("My side bar") | ||
|
||
# main function | ||
def main(): | ||
st.title("LLM Roleplay") | ||
|
||
if "submit" not in st.session_state: | ||
st.session_state.submit = False | ||
if "submit2" not in st.session_state: | ||
st.session_state.submit2 = False | ||
if "initial" not in st.session_state: | ||
st.session_state.initial = False | ||
if "initial2" not in st.session_state: | ||
st.session_state.initial2 = False | ||
if "extracted" not in st.session_state: | ||
st.session_state.extracted = False | ||
|
||
with st.form(key="form"): | ||
role1, role2 = st.columns([0.5, 0.5]) | ||
|
||
with role1: | ||
# role selection dropdown menu | ||
selected_roles_user = st.multiselect("Select User Roles", user_role_list) | ||
user = ', '.join(selected_roles_user) | ||
# user = st.text_input("User Role (EDIT ME)", value=', '.join(selected_roles_user)) | ||
|
||
with role2: | ||
# role selection dropdown menu | ||
selected_roles_assistant = st.multiselect("Select Assistant Roles", user_role_list) | ||
assistant = ', '.join(selected_roles_assistant) | ||
# assistant = st.text_input("Assistant Role (EDIT ME)", value=', '.join(selected_roles_assistant)) | ||
|
||
# input text for task | ||
# task = st.text_input("Topic") | ||
|
||
# input text for openAiKey | ||
openAiKey = st.text_input(label="Input the openai key", type="password") | ||
|
||
# form submit button and setting up the session_state | ||
if st.form_submit_button(label="Submit"): | ||
st.session_state.submit = True | ||
st.session_state.initial = True | ||
# print(user) | ||
# print(assistant) | ||
# print(prompt(user, assistant)) | ||
|
||
if st.session_state.submit: | ||
print("Inside submit") | ||
with st.spinner("In progress..."): | ||
try: | ||
if st.session_state.initial: | ||
st.session_state["task"] = task_generator(user, assistant, openAiKey) | ||
print("task_generator") | ||
# print("\n\n\nAfter the task\n\n\n") | ||
st.session_state.initial = False | ||
with st.form(key="form2"): | ||
|
||
# input text for task | ||
st.session_state["task"] = st.text_input("The topic for the roleplay (Edit if required)", value=st.session_state["task"]) | ||
|
||
if st.form_submit_button(label="Generate"): | ||
st.session_state.submit2 = True | ||
# print(st.session_state["task"]) | ||
st.session_state.initial2 = True | ||
# print("\n\nsubmit2 statues:") | ||
# print(st.session_state.submit2) | ||
# print("\n\n") | ||
except Exception as err: | ||
st.error(err) | ||
|
||
|
||
|
||
|
||
if st.session_state.submit2: | ||
print("Inside submit2") | ||
st.session_state.extracted = False | ||
with st.expander(label="role play"): | ||
with st.spinner("Generating..."): | ||
try: | ||
if st.session_state.initial2: | ||
|
||
roleplay, user_convo, assistant_convo = conversation_generator(user, assistant, st.session_state["task"]) | ||
# 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} | ||
st.session_state["roleplay"] = roleplay | ||
st.session_state.initial2 = False | ||
print("conversation_generator") | ||
# print("roleplay") | ||
# print(roleplay) | ||
# print("user_convo") | ||
# print(user_convo) | ||
# print("assistant_convo") | ||
# print(assistant_convo) | ||
st.session_state.extracted = True | ||
except Exception as err: | ||
st.error(err) | ||
|
||
if st.session_state.extracted: | ||
json_data = st.session_state["roleplay"] | ||
json_string = json.dumps(json_data, ensure_ascii=False) | ||
if st.download_button(label="Save as jsonl", data=json_string , mime="application/json"): | ||
st.success("Successfully saved") | ||
|
||
if st.button("Clear"): | ||
st.session_state.submit = False | ||
st.session_state.submit2 = False | ||
st.session_state.initial = False | ||
st.session_state.initial2 = False | ||
st.session_state.extracted = False | ||
if "task" in st.session_state: | ||
del st.session_state["task"] | ||
if "roleplay" in st.session_state: | ||
del st.session_state["roleplay"] | ||
st.experimental_rerun() | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,128 @@ | ||
import openai | ||
import streamlit as st | ||
from camel.agents import RolePlaying | ||
from camel.utils import print_text_animated | ||
from datetime import datetime | ||
|
||
|
||
|
||
def task_generator(user,assistant, openAiKey): | ||
|
||
openai.api_key = openAiKey | ||
|
||
prompt = f'''User: Farmer, Assistant: Business analyst | ||
Generate a conversation topic: Help the farmer in deciding the optimal choice for crops this year\n | ||
User: Accountant, Assistant: Developer | ||
Generate a conversation topic: Developing a custom accounting software to automate financial processes and reduce errors.\n | ||
User: Athlete, Assistant: Doctor | ||
Generate a conversation topic: Developing a personalized nutrition plan to optimize athletic performance and recovery.\n | ||
User: Politician, Assistant: Social Media Manager\n | ||
Generate a conversation topic: Develop a social media strategy to increase the politician's online presence and engagement with constituents.\n | ||
User: {user}, Assistant: {assistant} | ||
Generate a conversation topic:''' | ||
|
||
response = openai.Completion.create( | ||
engine="text-davinci-002", #Use gpt-3 engine. | ||
prompt=prompt, | ||
max_tokens=50, | ||
n=1 | ||
) | ||
task = response.choices[0].text.strip() | ||
|
||
return task | ||
|
||
def conversation_generator(user,assistant, task, chat_limit=2): | ||
task_prompt = task | ||
print(task) | ||
print(user) | ||
print(assistant) | ||
role_play_session = RolePlaying(assistant, user, task_prompt) | ||
# print(Fore.CYAN + f"Specified task prompt:\n{role_play_session.task_prompt}\n") | ||
# print(f"Specified task prompt:\n{role_play_session.task_prompt}\n") | ||
|
||
chat_turn_limit, n = chat_limit, 0 | ||
assistant_msg, _ = role_play_session.init_chat() | ||
|
||
user_chat = [] | ||
assistant_chat = [] | ||
now = datetime.now() | ||
|
||
current_time = now.strftime("%H:%M:%S") | ||
print("Current Time =", current_time) | ||
|
||
while n < chat_turn_limit: | ||
n += 1 | ||
try: | ||
(assistant_msg, _, _), (user_msg, _, _) = role_play_session.step(assistant_msg) | ||
assert user_msg.content is not None | ||
with st.chat_message("user"): | ||
user_content = user_msg.content.replace("Instruction: ", "").replace("Input: None", "") | ||
st.text(user_content) | ||
assert assistant_msg.content is not None | ||
with st.chat_message("assistant"): | ||
assistant_content = assistant_msg.content.replace("Solution: ", "").replace("Next request.","") | ||
st.text(assistant_content) | ||
|
||
except: | ||
break | ||
|
||
# print(Fore.BLUE + f"AI User:\n\n{user_msg.content}\n\n") | ||
# print(f"AI User:\n\n{user_msg.content}\n\n") | ||
user_chat.append(user_msg.content) | ||
if "Next request." not in assistant_msg.content: | ||
break | ||
|
||
# print(Fore.GREEN + f"AI Assistant:\n\n{assistant_msg.content}\n\n") | ||
# print(f"AI Assistant:\n\n{assistant_msg.content}\n\n") | ||
assistant_chat.append(assistant_msg.content) | ||
if "<CAMEL_TASK_DONE>" in user_msg.content: | ||
break | ||
|
||
#Processing the generated conversation | ||
|
||
final_user_convo = [] | ||
final_assistant_convo = [] | ||
|
||
if len(assistant_chat)==0 or len(user_chat)==0: | ||
return "Empty list" | ||
|
||
|
||
for i in range(len(user_chat)): | ||
|
||
if ("Next request" in assistant_chat[i]) and ("Instruction:" in user_chat[i]) and ("Input:" in user_chat[i]): | ||
final_instruction = "" | ||
try: | ||
instruction = user_chat[i].split("Instruction:")[1].split("Input:")[0] | ||
input = user_chat[i].split("Input:")[1].strip() | ||
except: | ||
continue | ||
|
||
if input.strip() == 'None': | ||
final_instruction = final_instruction+instruction.replace("\n"," ") | ||
final_instruction = final_instruction.strip() | ||
else: | ||
final_instruction = instruction.replace("\n"," ")+"\ninput:"+input #If an input is there, then add a newline after instruction, input: and then the input. | ||
final_instruction = final_instruction.strip() | ||
|
||
final_user_convo.append(final_instruction) | ||
final_assistant_convo.append(assistant_chat[i].replace("Solution:","").replace("Next request.","").strip()) | ||
|
||
else: | ||
break #Sometimes faulty chat gets generated. A proper convo has Next request at the end | ||
|
||
assert (len(final_user_convo)-len(assistant_chat))<=1 | ||
# print('\n\n'+'End of the conversation\n\n') | ||
# print("*"*150, end='\n') | ||
final_convo_list = [] | ||
|
||
for i in range(len(final_user_convo)): | ||
user_convo = {"from":"user","value":final_user_convo[i]} | ||
assistant_convo = {"from":"assistant","value":final_assistant_convo[i]} | ||
final_convo_list.append(user_convo) | ||
final_convo_list.append(assistant_convo) | ||
|
||
length = len(final_convo_list) | ||
|
||
final_json_entry = {'user':user,'assistant':assistant,'task':task_prompt,'conversations':final_convo_list, 'specified_task':role_play_session.task_prompt, 'length':length} | ||
# pprint.pprint(final_json_entry) | ||
return final_json_entry, final_user_convo, final_assistant_convo |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
streamlit | ||
openai |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
user_role_list = ['AI Researcher', 'Accountant', 'Actor', 'Actress', 'Archaeologist', 'Archivist', 'Architect', 'Artist', 'Astronomer', | ||
'Athlete', 'Author', 'Barista', 'Bartender', 'Biologist', 'Biomedical Engineer', 'Blogger', 'CEO', 'Carpenter', 'Cartoonist', | ||
'Chef', 'Chauffeur', 'Counselor', 'Customer', 'DJ', 'Dancer', 'Data Analyst', 'Dentist', 'Designer', 'Director', 'Doctor', 'Electrician', | ||
'Engineer', 'Entrepreneur', 'Environmentalist', 'Ethical Hacker', 'Event Planner', 'Explorer', 'Farmer', 'Fashion Model', 'Financial Analyst', | ||
'Firefighter', 'Fitness Coach', 'Florist', 'Gamer', 'Geologist', 'Graphic Designer', 'Hair Stylist', 'Historian', 'Housekeeper', 'Illustrator', | ||
'Lawyer', 'Librarian', 'Magician', 'Magistrate', 'Makeup Artist', 'Manager', 'Mechanic', 'Meteorologist', 'Musician', 'News Reporter', 'Novelist', | ||
'Nurse', 'Nutritionist', 'Parent', 'Personal Trainer', 'Pharmacist', 'Philanthropist', 'Philosopher', 'Photographer', 'Pilot', 'Plumber', 'Poet', | ||
'Police Officer', 'Producer', 'Psychologist', 'Real Estate Agent', 'Receptionist', 'Researcher', 'Salesperson', 'Scientist', 'Superintendent', 'Security guard', | ||
'Social Media Influencer', 'Social Worker', 'Software Engineer', 'Sommelier', 'Student', 'Taxi Driver', 'Teacher', 'Therapist', 'Tour Guide', 'Translator', | ||
'Traveler', 'Veterinarian', 'Waiter', 'Web Developer', 'Wedding Planner', 'Writer', 'Yoga Instructor', 'Zoologist'] |