import gradio as gr from langchain.chains import LLMChain from langchain.chains import SimpleSequentialChain from langchain.llms import OpenAI from langchain.prompts import PromptTemplate from langchain.chains import SequentialChain import openai import os import base64 import requests import json openai.api_key = os.getenv("OPENAI_API_KEY") def getAndParseQuickStart(text): print("Asking AI for a character of " + text) prompt = """ Please generate a character based on the following description assuming this is a real person, make sure any dialog is accurate as to how this specific character sounds. The dialog should give a good indication of the manner in which the character speaks:\n """ + text response = openai.ChatCompletion.create( model="gpt-3.5-turbo-0613", messages=[ {"role": "system", "content": instruction_prompt}, {"role": "user", "content": prompt} ]) #print(response) # Parse the AI's response response_content = response['choices'][0]['message']['content'] print(response_content) example_chat_index = response_content.find('Example_Chat:') if example_chat_index != -1: # Extract 'Example Chat' and everything after it example_chat_content = response_content[example_chat_index:] # Split the content into lines example_chat_lines = example_chat_content.split('\n') # The first line is 'Example Chat: ' # So we need to remove 'Example Chat: ' from it example_chat_lines[0] = example_chat_lines[0][len('Example_Chat: '):] # Join the lines back together to get the full 'Example Chat' example_chat = '\n'.join(example_chat_lines) traits_dict = {'Example_Chat': example_chat.strip()} # Remove the 'Example Chat' part from the response content so it won't be processed again in the loop api_response = response_content[:example_chat_index] else: traits_dict = {} traits = response_content.split('\n') print(traits) raw = traits #print(locked_fields) for trait in traits: if ': ' in trait: key, value = trait.split(': ', 1) # Split at the first occurrence of ': ' key = key.lower() key = key.replace(' ', '_') #if key in locked_fields: # continue if key == 'name': traits_dict[key.capitalize()] = value elif key == 'first_message': traits_dict['First_Message'] = value elif key == 'personality_summary': traits_dict['Personality_Summary'] = value else: traits_dict[key.capitalize()] = value charName = traits_dict.get('Name', '') personality = traits_dict.get('Personality', '') body = traits_dict.get('Body', '') likes = traits_dict.get('Likes', '') hates = traits_dict.get('Hates', '') sex = traits_dict.get('Sex', '') sexuality = traits_dict.get('Sexuality', '') age = traits_dict.get('Age', '') description = traits_dict.get('Description', '') personalityProfile = traits_dict.get('Personality_Profile', '') attributes = traits_dict.get('Attributes', '') return [ raw, charName, personality, body, likes, hates, sex, sexuality, age, description, personalityProfile, attributes ] def generateSpeakingStyle(text): print("Asking AI for a speaking style from:\n" + text) prompt = """ Here is a detailed summary of a character:\n """ + text + """ \n Based on that, determine the speaking style that would best express how this character would talk. For each of the following, choose the best option for this character: """ + prompt_Personality + """ Please return your choices in JSON format: {"property":"choice", "property":"choice", ....etc}\n Do not change any capitalization. Do not include any new lines. Only a correct JSON format. """ response = openai.ChatCompletion.create( model="gpt-4-0613", messages=[ {"role": "system", "content": "You are a world-class writer and character designer."}, {"role": "user", "content": prompt} ]) print(response) response_content = response['choices'][0]['message']['content'] response = json.loads(response_content) return [ response.get('formality', ''), response.get('pace', ''), response.get('rhythm', ''), response.get('volume', ''), response.get('emotionality', ''), response.get('directness', ''), response.get('humor', ''), response.get('enunciation', ''), response.get('expressiveness', ''), response.get('accent', ''), response.get('politeness', ''), response.get('vocabulary', ''), response.get('interruptions', ''), response.get('hesitations', ''), response.get('sentence structure', ''), response.get('sarcasm', ''), response.get('colloquialisms', ''), response.get('energy level', ''), response.get('defiance/rebellion', ''), response.get('playfulness', ''), response.get('vulgarity', ''), response.get('idiosyncrasies', ''), response.get('emotional tone', ''), response.get('context adaptability', ''), response.get('subtext', ''), response.get('metaphorical language', ''), response.get('cultural references', ''), response.get('storytelling ability', '') ] with gr.Blocks() as demo: with gr.Row(): quickStart = gr.TextArea(label="Quick Start", info="Use AI to fill out all fields based on your description.") generate = gr.Button("Generate") quickStartResult = gr.TextArea(label="result", interactive=False) with gr.Row(): with gr.Column(scale=1, min_width=600): charName = gr.Textbox(label="Name", interactive=True) personality = gr.Textbox(label="Personality", interactive=True) body = gr.Textbox(label="Physical Description", interactive=True) with gr.Row(): likes = gr.Textbox(label="Likes", interactive=True) hates = gr.Textbox(label="Hates", interactive=True) with gr.Row(): sex = gr.Dropdown(["Male", "Female", "Other"], label="Sex", interactive=True) sexuality = gr.Textbox(label="Sexuality", interactive=True) age = gr.Slider(1, 100, label="Age", info="Choose between 1 and 100", interactive=True, step=1.0) description = gr.Textbox(label="Description", interactive=True) attributes = gr.Textbox(label="Attributes", interactive=True) with gr.Row(): personalityProfile = gr.Textbox(label="Personality Profile", interactive=True) generatePersonality = gr.Button("Analyze") with gr.Accordion("Speaking Traits"): genProfile = gr.Button("Generate Speaking Style", interactive=True) with gr.Column(scale=1, min_width=600): with gr.Row(): formality = gr.Dropdown(["Very formal", "Formal", "Neutral", "Informal", "Very informal"], label="Formality", interactive=True) pace = gr.Dropdown(["Very fast", "Fast", "Moderate", "Slow", "Very slow"], label="Pace", interactive=True) rhythm = gr.Dropdown(["Choppy", "Staccato", "Varied", "Flowing", "Melodious"], label="Rhythm", interactive=True) volume = gr.Dropdown(["Very loud", "Loud", "Moderate", "Soft", "Very soft"], label="Volume", interactive=True) emotionality = gr.Dropdown(["Very expressive", "Expressive", "Neutral", "Restrained", "Very restrained"], label="Emotionality", interactive=True) directness = gr.Dropdown(["Very direct", "Direct", "Balanced", "Indirect", "Very indirect"], label="Directness", interactive=True) with gr.Row(): humor = gr.Dropdown(["Frequently humorous", "Occasionally humorous", "Neutral", "Occasionally serious", "Frequently serious"], label="Humor", interactive=True) enunciation = gr.Dropdown(["Very clear", "Clear", "Neutral", "Relaxed", "Mumbled"], label="Enunciation", interactive=True) expressiveness = gr.Dropdown(["Very expressive", "Expressive", "Neutral", "Reserved", "Very reserved"], label="Expressiveness", interactive=True) accent_dialect = gr.Dropdown(["Strong regional accent", "Mild regional accent", "Neutral", "Mild foreign accent", "Strong foreign accent"], label="Accent/Dialect", interactive=True) politeness = gr.Dropdown(["Very polite", "Polite", "Neutral", "Blunt", "Very blunt"], label="Politeness", interactive=True) vocabulary = gr.Dropdown(["Highly sophisticated", "Sophisticated", "Average", "Basic", "Very basic"], label="Vocabulary", interactive=True) with gr.Row(): interruptions = gr.Dropdown(["Frequently interrupts", "Occasionally interrupts", "Balanced", "Occasionally allows others to interrupt", "Frequently allows others to interrupt"], label="Interruptions", interactive=True) hesitations = gr.Dropdown(["Frequently hesitates", "Occasionally hesitates", "Balanced", "Occasionally fluent", "Frequently fluent"], label="Hesitations", interactive=True) sentence_structure = gr.Dropdown(["Very complex", "Complex", "Average", "Simple", "Very simple"], label="Sentence Structure", interactive=True) sarcasm = gr.Dropdown(["Very sarcastic", "Sarcastic", "Occasionally sarcastic", "Rarely sarcastic", "Never sarcastic"], label="Sarcasm", interactive=True) colloquialisms = gr.Dropdown(["Frequently uses colloquialisms", "Occasionally uses colloquialisms", "Balanced", "Rarely uses colloquialisms", "Never uses colloquialisms"], label="Colloquialisms", interactive=True) energy_level = gr.Dropdown(["Very high energy", "High energy", "Moderate energy", "Low energy", "Very low energy"], label="Energy Level", interactive=True) with gr.Row(): defiance_rebellion = gr.Dropdown(["Frequently defiant", "Occasionally defiant", "Balanced", "Rarely defiant", "Never defiant"], label="Defiance/Rebellion", interactive=True) playfulness = gr.Dropdown(["Very playful", "Playful", "Occasionally playful", "Rarely playful", "Never playful"], label="Playfulness", interactive=True) vulgarity = gr.Dropdown(["Very vulgar", "Vulgar", "Occasionally vulgar", "Rarely vulgar", "Never vulgar"], label="Vulgarity", interactive=True) idiosyncrasies = gr.Dropdown(["Frequent idiosyncrasies", "Occasional idiosyncrasies", "Balanced", "Rare idiosyncrasies", "No idiosyncrasies"], label="Idiosyncrasies", interactive=True) emotional_tone = gr.Dropdown(["Very optimistic", "Optimistic", "Neutral", "Pessimistic", "Very pessimistic"], label="Emotional Tone", interactive=True) context_adaptability = gr.Dropdown(["Very adaptable", "Adaptable", "Balanced", "Inflexible", "Very inflexible"], label="Context Adaptability", interactive=True) with gr.Row(): subtext = gr.Dropdown(["Frequently uses subtext", "Occasionally uses subtext", "Balanced", "Rarely uses subtext", "Never uses subtext"], label="Subtext", interactive=True) metaphorical_language = gr.Dropdown(["Frequently uses metaphorical language", "Occasionally uses metaphorical language", "Balanced", "Rarely uses metaphorical language", "Never uses metaphorical language"], label="Metaphorical Language", interactive=True) cultural_references = gr.Dropdown(["Frequently uses cultural references", "Occasionally uses cultural references", "Balanced", "Rarely uses cultural references", "Never uses cultural references"], label="Cultural References", interactive=True) storytelling_ability = gr.Dropdown(["Frequent storyteller", "Occasional storyteller", "Balanced", "Rarely tells stories", "Never tells stories"], label="Storytelling Ability", interactive=True) with gr.Column(scale=1, min_width=600): situation = gr.TextArea(label="Situation", interactive=True) starting_message = gr.TextArea(label="Starting message", interactive=True) sample_starters = gr.CheckboxGroup(["This year is flying by so fast.", "It's quite sunny outside today.", "People seem to be in a hurry all the time.", "I hear birds chirping. It must be spring already.", "The city looks different at night."], label="Example conversation starters", info="These are simple statements designed to evoke a unique response without adding additional context. ", interactive=True), with gr.Row(): with gr.Column(scale=1): addUser = gr.Button("{{user}} >>") addBot = gr.Button("{{char}} >>") with gr.Column(scale=6): examples = gr.TextArea(label="Example chats", value="\n") def test(): print("trying....") state = demo.state state.inputs["charName"] = "New Name" demo.update(state) generate.click(getAndParseQuickStart, inputs=[quickStart], outputs=[ quickStartResult, charName, personality, body, likes, hates, sex, sexuality, age, description, personalityProfile, attributes ]) createJSON = gr.Button("Create JSON") def makePersonality(text): print("Asking AI for a profile") prompt = "Here are the details for you to analyze. Remember to return in the specified format: " + text response = openai.ChatCompletion.create( model="gpt-4-0613", messages=[ {"role": "system", "content": prompt_profile}, {"role": "user", "content": prompt} ]) response_content = response['choices'][0]['message']['content'] print(response_content) return response_content generatePersonality.click(makePersonality, inputs=[quickStartResult], outputs=[personalityProfile]) def insertUser(text): return text + "\n{{user}}" def insertBot(text): return text + "\n{{char}}" addUser.click(insertUser, inputs=[examples], outputs=examples) addBot.click(insertBot, inputs=[examples], outputs=examples) genProfile.click(generateSpeakingStyle, inputs=[quickStartResult], outputs=[ formality, pace, rhythm, volume, emotionality, directness, humor, enunciation, expressiveness, accent_dialect, politeness, vocabulary, interruptions, hesitations, sentence_structure, sarcasm, colloquialisms, energy_level, defiance_rebellion, playfulness, vulgarity, idiosyncrasies, emotional_tone, context_adaptability, subtext, metaphorical_language, cultural_references, storytelling_ability ]) def createJSONfile(quickStartResult, charName, personality, body, likes, hates, sex, sexuality, age, description, personalityProfile, attributes, formality, pace, rhythm, volume, emotionality, directness, humor, enunciation, expressiveness, accent_dialect, politeness, vocabulary, interruptions, hesitations, sentence_structure, sarcasm, colloquialisms, energy_level, defiance_rebellion, playfulness, vulgarity, idiosyncrasies, emotional_tone, context_adaptability, subtext, metaphorical_language, cultural_references, storytelling_ability): ### Merging things into description description_unwrapped = f""" {charName} is a {age}-year-old {sexuality} {sex}.\n {description}.\n {charName} is {body}.\n {charName} likes {likes}.\n {charName} hates {hates}.\n """ speech_unwrapped = f""" {charName} speaks with a unique style: They {"are " + formality + " and" if formality!="Neutral" else ""} and speaks at a {pace} speed with a {rhythm} rhythm. {charName} {"speaks at a " + volume + " volume and " if volume!="Moderate" else ""}has a {emotionality} level of emotionality. {charName + " is " + directness + "." if directness!="Balanced" else ""} {charName + " is " + humor + "." if humor!="Neutral" else ""} Their clarity of speech is {enunciation} {charName + " is " + expressiveness + "." if expressiveness!="Neutral" else ""} They have a {accent_dialect} accent. {charName} {"is " + politeness + " and " if politeness!="Neutral" else ""}uses a {vocabulary} vocabulary. {"They " + interruptions + "." if interruptions!="Balanced" else ""} {"They " + hesitations + "." if interruptions!="Balanced" else ""} {charName} uses a {sentence_structure} sentence structure and is {sarcasm} {"They " + colloquialisms + "." if colloquialisms!="Balanced" else ""} They speak with {energy_level}{" and is " + defiance_rebellion + "." if defiance_rebellion!="Balanced" else "."} When {charName} speaks it is {playfulness} and {vulgarity}. {charName + " uses " + idiosyncrasies + "." if idiosyncrasies!="Balanced" else ""} They have a {emotional_tone} tone {charName + " is " + context_adaptability + " when the situation changes." if context_adaptability!="Balanced" else ""} {"They " + subtext + "." if subtext!="Balanced" else ""} {"They " + metaphorical_language + "." if metaphorical_language!="Balanced" else ""} {"They " + cultural_references + "." if cultural_references!="Balanced" else ""} {"They " + storytelling_ability + "." if storytelling_ability!="Balanced" else ""} """ output = f"""{{"name": "{charName}", "personality": "{personality}", "description": "{description_unwrapped}", "speech_style": "{speech_unwrapped}" }}""" print(output) return output createJSON.click(createJSONfile, inputs=[ quickStartResult, charName, personality, body, likes, hates, sex, sexuality, age, description, personalityProfile, attributes, formality, pace, rhythm, volume, emotionality, directness, humor, enunciation, expressiveness, accent_dialect, politeness, vocabulary, interruptions, hesitations, sentence_structure, sarcasm, colloquialisms, energy_level, defiance_rebellion, playfulness, vulgarity, idiosyncrasies, emotional_tone, context_adaptability, subtext, metaphorical_language, cultural_references, storytelling_ability ], outputs=[quickStartResult]) instruction_prompt = """ You are an AI bot that creates profiles of characters based on a simple input. You generate and give detailed characters in the following format: Name: descriptors Mind: descriptors (comma separated properties) Personality: descriptors (comma separated properties, at least 8 traits) Body: descriptors (comma separated properties, at least 8 traits) Likes: descriptors (comma separated properties, at least 8 traits) Hates: descriptors (comma separated properties, at least 8 traits) Attributes: descriptors (comma separated properties, at least 8 traits) Clothes: descriptors (comma separated properties) Sex: descriptor (Male, Female, or Other) Sexuality: descriptor (Gay, Straight, Bi, or Asexual) Age: descriptor (as an integer, no additional text) Description: descriptor (3 sentences) Personality_Summary: descriptor """ prompt_chat_test = """ Scenario: descriptor (Minimum 4 sentences) First_Message: descriptor (do not include any quotation marks. At least 3 sentences) Example_Chat: descriptor (do not print names or quotation marks, only use the format of starting with > for the user name and >> for the character name, for example: >Hi\n>>Hello! **i pick up a book**\n>What's up? What are you reading?\n>>**Looks at the book cover** Nothing much)""" prompt_Personality = """ formality (level of formal language use): Very formal, Formal, Neutral, Informal, Very informal\n pace (speed of speech): Very fast, Fast, Moderate, Slow, Very slow\n rhythm (pattern of speech): Choppy, Staccato, Varied, Flowing, Melodious\n volume (loudness of speech): Very loud, Loud, Moderate, Soft, Very soft\n emotionality (level of emotional expression): Very expressive, Expressive, Neutral, Restrained, Very restrained\n directness (level of straightforwardness): Very direct, Direct, Balanced, Indirect, Very indirect\n humor (frequency of humor in speech): Frequently humorous, Occasionally humorous, Neutral, Occasionally serious, Frequently serious\n enunciation (clarity of speech): Very clear, Clear, Neutral, Relaxed, Mumbled\n expressiveness (use of gestures and body language): Very expressive, Expressive, Neutral, Reserved, Very reserved\n accent (type of accent or dialect): Strong regional accent, Mild regional accent, neutral, Mild foreign accent, Strong foreign accent\n politeness (degree of politeness): Very polite, Polite, Neutral, Blunt, Very blunt\n vocabulary (range and type of words used): Highly sophisticated, Sophisticated, Average, Basic, Very basic\n interruptions (frequency of interruptions): Frequently interrupts, Occasionally interrupts, Balanced, Occasionally allows others to interrupt, Frequently allows others to interrupt\n hesitations (frequency of pauses or fillers): Frequently hesitates, Occasionally hesitates, Balanced, Occasionally fluent, Frequently fluent\n sentence structure (complexity of sentences): Very complex, Complex, Average, Simple, Very simple\n sarcasm (frequency and intensity of sarcasm): Very sarcastic, Sarcastic, Occasionally sarcastic, Rarely sarcastic, Never sarcastic\n colloquialisms (use of slang or colloquial language): Frequently uses colloquialisms, Occasionally uses colloquialisms, Balanced, Rarely uses colloquialisms, Never uses colloquialisms\n energy level (level of enthusiasm or intensity in speech): Very high energy, High energy, Moderate energy, Low energy, Very low energy\n defiance/rebellion (tendency to challenge or question things in speech): Frequently defiant, Occasionally defiant, Balanced, Rarely defiant, Never defiant\n playfulness (exhibits a playful tone in speech): Very playful, Playful, Occasionally playful, Rarely playful, Never playful\n vulgarity (frequency and intensity of crude language or coarse expressions): Very vulgar, Vulgar, Occasionally vulgar, Rarely vulgar, Never vulgar\n idiosyncrasies (unique speech habits or quirks): Frequent idiosyncrasies, Occasional idiosyncrasies, Balanced, Rare idiosyncrasies, No idiosyncrasies\n emotional tone (overall emotional 'color' of the character's speech): Very optimistic, Optimistic, Neutral, Pessimistic, Very pessimistic\n context adaptability (how a character's speech changes depending on the situation or person they're speaking to): Very adaptable, Adaptable, Balanced, Inflexible, Very inflexible\n subtext (the underlying, implied meaning in a character's speech): Frequently uses subtext, Occasionally uses subtext, Balanced, Rarely uses subtext, Never uses subtext\n metaphorical language (use of metaphors, similes, and other figurative language in a character's speech): Frequently uses metaphorical language, Occasionally uses metaphorical language, Balanced, Rarely uses metaphorical language, Never uses metaphorical language\n cultural references (references to their culture, such as idioms, phrases, or words from their native language, references to cultural practices or beliefs): Frequently uses cultural references, Occasionally uses cultural references, Balanced, Rarely uses cultural references, Never uses cultural references\n storytelling ability (frequency of telling stories or anecdotes in their speech): Frequent storyteller, Occasional storyteller, Balanced, Rarely tells stories, Never tells stories\n """ prompt_profile = """ Based on your understanding of this character, please provide a brief personality assessment using the following typologies: Myers-Briggs Type Indicator (MBTI): Introverted/Extraverted, Sensing/Intuitive, Thinking/Feeling, Judging/Perceiving. Enneagram: main type, wing, and instinctual variant (self-preservation/sp, social/so, or sexual/sx). Enneagram Tritype: two additional types from different centers of intelligence. Socionics: similar to MBTI, identify the character's personality type. Global 5/SLOAN: Reserved/Social, Calm/Limbic, Organized/Unstructured, Accommodating/Egocentric, Non-Curious/Inquisitive. Please return the result codes in this format: "MBTI - Enneagram - Instinctual Variant - Tritype - Socionics - SLOAN". For example: INTJ - 3w4 - sp/sx - 358 - LIE - RCOEI". Do not explain or add other text or context. """ inst = demo.launch()