Spaces:
Runtime error
Runtime error
Download Chatbot_new.py from Tiliah/condition1: direct link, hf CLI and curl.
- Browser
- Download file 55.1 kB
-
https://huggingface.co/spaces/Tiliah/condition1/resolve/main/Chatbot_new.py
- Command line
-
hf download hf://spaces/Tiliah/condition1/Chatbot_new.py
-
curl -L -o Chatbot_new.py https://huggingface.co/spaces/Tiliah/condition1/resolve/main/Chatbot_new.py
55.1 kB
import os
import openai
import random
import pandas as pd
import uuid
import pickle
# Module seeds
context_types = {
"Work/Professional": [
"Working on a project or task",
"Attending a meeting or briefing",
"Collaborating with colleagues or team members",
"Presenting a proposal or idea",
"Responding to client or customer feedback",
"Managing or resolving a workplace conflict",
"Negotiating a contract or agreement",
"Performing routine tasks",
"Handling unexpected challenges"
],
"Social": [
"Engaging in a social gathering or event",
"Having a one-on-one conversation with a friend or acquaintance",
"Participating in a group activity or hobby",
"Sharing ideas or opinions in a casual discussion",
"Dealing with a social conflict or disagreement",
"Networking at a professional or social event"
],
"Physical Activity": [
"Participating in a team sport or physical competition",
"Engaging in an outdoor activity",
"Training or practicing with a coach or instructor",
"Competing in a tournament or race",
"Engaging in a personal fitness routine or challenge",
"Performing a physical task that requires coordination or teamwork"
],
"Reflection": [
"Reflecting on a past decision or action",
"Planning future goals or strategies",
"Evaluating personal or professional progress",
"Contemplating a challenging situation or conflict",
"Revisiting a difficult conversation or interaction",
"Assessing personal strengths, weaknesses, or skills"
],
"Educational": [
"Participating in a class, lecture, or seminar",
"Collaborating on a study project or research",
"Receiving feedback from a teacher or mentor",
"Preparing for or taking an exam",
"Engaging in group study or discussion",
"Presenting academic work or research findings"
],
"Creative": [
"Working on a creative project",
"Collaborating with others on a creative endeavor",
"Receiving feedback on a creative piece",
"Presenting a creative work to an audience",
"Brainstorming or ideating new concepts",
"Experimenting with new techniques or styles"
]
}
interaction_types = {
"Authority Feedback": [
"Receiving feedback or critique from a supervisor, boss, or mentor",
"Listening to advice or guidance from a coach or teacher",
"Engaging in a performance review or evaluation",
"Responding to managerial decisions or directives"
],
"Peer Reaction": [
"Receiving input, advice, or reactions from a colleague, friend, or teammate",
"Discussing ideas or opinions with peers in a group setting",
"Addressing concerns, compliments, or criticisms from a peer",
"Collaborating on a task or project with equal responsibility"
],
"Group Dynamics": [
"Participating in a group discussion or brainstorming session",
"Leading or following in a team activity or project",
"Managing group feedback or collective opinions",
"Navigating differing opinions, conflicts, or agreements within a group"
],
"Self-Reflection": [
"Analyzing personal decisions, actions, or behaviors",
"Contemplating improvements or changes based on past experiences",
"Reflecting on feedback received from others",
"Re-evaluating personal goals, priorities, or values"
],
"Creative Feedback": [
"Seeking opinions or critiques on a creative project from peers or mentors",
"Engaging in a discussion about a creative piece's direction or style",
"Presenting creative work to a group and receiving diverse reactions"
],
"Social Participation": [
"Engaging in a group activity or event related to a hobby or interest",
"Discussing or sharing personal achievements or interests in a social setting",
"Navigating group dynamics during a leisure activity or social gathering"
]
}
tones = ["Positive", "Negative"]
actions_events = {
"Work/Professional": [
"Receiving feedback",
"Observing reactions",
"Presenting ideas",
"Responding to a situation"
],
"Creative/Personal Projects": [
"Completing a creative project",
"Seeking feedback",
"Engaging in competition",
"Sharing achievements"
],
"Social/Leisure Activities": [
"Socializing at an event",
"Participating in a hobby",
"Competing in a friendly match",
"Celebrating an achievement"
]
}
outcomes_reveals = {
"Feedback Becomes More Detailed": [
"The feedback received becomes more specific, highlighting both strengths and weaknesses",
"Additional information is provided about how your work or actions have been perceived"
],
"Reactions Evolve": [
"Others in the group or interaction begin to share their thoughts, leading to a broader or more complex discussion",
"A different or unexpected perspective is introduced, challenging initial reactions or assumptions"
],
"Situation Becomes More Complex": [
"A new element or complication is introduced, adding layers to the initial problem or challenge",
"Additional context or background information is revealed, shifting the interpretation of the situation"
],
"Personal Reflection Deepens": [
"You start to see patterns or broader implications of your actions or decisions",
"A realization or new insight occurs that changes how you view the initial event or scenario"
]
}
def interpret_response(user_input, options_text, user_state):
stage = user_state.get("stage", "")
if stage == "internal_external":
# Expecting a numeric rating from 1 to 10
try:
rating = int(user_input)
if 1 <= rating <= 5:
return '1' # Option 1: Internal factors are more likely
elif 6 <= rating <= 10:
return '2' # Option 2: External factors are more likely
else:
return "Please clarify."
except ValueError:
return "Please clarify."
else:
# Existing logic for other stages
prompt = f"""
You are tasked with interpreting user responses to multiple-choice questions.
Options provided:
{options_text}
User's response: "{user_input}"
Identify the matching option number (e.g., '1', '2', etc.) based on the options.
Respond with the option number only.
If the user's response is unclear or doesn't match any option, respond with "Please clarify.".
"""
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
temperature=0.3,
max_tokens=5
)
assistant_response = response.choices[0].message.content.strip()
print(f"interpret_result() output: {assistant_response}")
# Validate the response
option_numbers = [str(i) for i in range(1, len(options_text.split('\n')) + 1)]
if assistant_response in option_numbers:
return assistant_response
elif assistant_response.lower() == "please clarify.":
return "Please clarify."
else:
return "Invalid response."
def standardize_response(question, response):
prompt_lower = question.lower()
if "scale from 1 to 10" in prompt_lower:
try:
rating = int(response)
if 1 <= rating <= 10:
return rating # Return as integer for consistency
else:
return None
except ValueError:
return None
# Handle other questions as before
else:
prompt = f"""
Standardize the following user response for analysis:
Question: "{question}"
User Response: "{response}"
Extract the key information relevant to the question and provide it as a standardized response.
Examples:
- Age: "I'm 25 years old" → "25"
- Profession: "I work as a teacher" → "teacher"
- Interests: "I enjoy hiking and painting" → "hiking, painting"
Respond with only the standardized response. Do not include any additional text or explanations.
"""
standardized_response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are an assistant standardizing user responses for data analysis."},
{"role": "user", "content": prompt}
],
temperature=0.1
).choices[0].message.content.strip()
print(f"standardize_response() output: {standardized_response}")
if standardized_response.lower().startswith("standardized response:"):
standardized_response = standardized_response.split(":", 1)[1].strip()
# Validate the format based on the question type
if "age" in question.lower() and standardized_response.isdigit():
return int(standardized_response)
elif "profession" in question.lower():
return standardized_response
elif "interests" in question.lower():
return standardized_response
else:
return standardized_response
# def load_vignette_data(vignette_number, user_state):
# """
# Fetches the vignette and reveal for a given participant from the Excel file.
# Arguments:
# - vignette_number: The specific vignette number (1 to 16)
# Returns:
# - vignette_text: The text of the vignette for the selected participant
# - tone: The tone associated with the vignette (e.g., Positive or Negative)
# - first_reveal: The first reveal for the given vignette
# """
# # Load the Excel data
# data = pd.read_excel("assessment_data.xlsx")
# # Select a random user ID if it's not set yet
# if selected_user_id is None:
# user_ids = data['User ID'].unique()
# if len(user_ids) == 0:
# print("No User IDs found in the assessment data.")
# return None, None, None
# selected_user_id = random.choice(user_ids)
# # Filter the data based on selected_user_id and vignette_number
# user_data = data[(data['User ID'] == selected_user_id) & (data['Vignette Number'] == vignette_number)]
# if not user_data.empty:
# vignette_text = user_data['Vignette'].values[0]
# tone = user_data['Tone'].values[0]
# first_reveal = user_data['First Reveal'].values[0]
# return vignette_text, tone, first_reveal
# else:
# print(f"No data found for user_id {selected_user_id} and vignette {vignette_number}")
# return None, None, None
# Function to generate the vignette
def generate_vignette(chat_history, topic_choice, desired_tone, user_state):
# Extract user profile from standardized data
user_profile = user_state.get("standardized_data", {})
user_age = user_profile.get("Age", "Unknown")
user_profession = user_profile.get("Profession", "Unknown")
user_interests = user_profile.get("Interests", "Unknown")
# Build the prompt to select modules and generate the vignette
prompt = f"""
Based on the user's profile and preferences, create a vignette tailored to the following details:
- Age: {user_age}
- Profession: {user_profession}
- Interests: {user_interests}
- Chat history: {chat_history}
Select the most appropriate modules from these categories to create a relatable situation:
- Context type (Work/Professional, Social, Physical Activity, Reflection, Educational, Creative)
- Interaction type (Authority Feedback, Peer Reaction, Group Dynamics, Creative Feedback, Social Participation, Conflict/Disagreement, Support Interaction)
- Tone (Must be either clearly Positive or clearly Negative!)
- Action/Event (Receiving Feedback, Observing Reactions, Presenting Ideas, Responding to a Situation, Completing a Creative Project, Seeking Feedback, Engaging in Competition, Sharing Achievements, Socializing at an Event, Competing in a Friendly Match, Celebrating an Achievement, Providing/Receiving Emotional Support, Conflict Resolution, Handling Unexpected Situations, Facing Disapproval)
Use these selected modules to generate a vignette for a psychological assessment.
Guidelines:
- Analyze the conversation history to understand the user's age, profession, and interests.
- **The user has chosen topic {topic_choice}:**
- **If the user chose '1', focus on a situation related to their profession.**
- **If the user chose '2', focus on a situation related to their personal interests.**
- **If the user chose '3', focus on a situation related to their most recent input in the {chat_history}.**
Only select one module per category.
The selected tone should clearly shape the atmosphere of the scenario and remain consistent throughout the vignette.
Avoid mixed tones.
Keep the vignettes fresh and varied.
Consider all clarifying information the user has provided throughout the {chat_history} when creating a vignette.
Do not include the module names or categories in the output.
Only provide the vignette text and do not include phrases like "Sure", "Here is your vignette", or any other extra text.
Ensure that the vignette is directly related to the user's profile and context. **Focus on describing the external events without including any inner reflections, thoughts, or feelings.**
**Do not mention how the user feels or thinks about the situation.**
Describe the vignette in a second-person view.
Keep the vignette concise, under a 50-token limit.
Use neutral and professional but simple language suitable for a psychological assessment.
Do not include any personal identifying information.
"""
# Prepare the messages for the API call
messages = [
{"role": "system", "content": """
You are tasked with selecting appropriate modules and generating a standardized vignette for a psychological assessment.
The vignette should assess attribution styles across three dimensions: Internal-External, Stable-Unstable, and Global-Specific.
"""},
{"role": "user", "content": prompt}
]
# Append the conversation history to the messages
for message in chat_history:
messages.append(message)
# Call the OpenAI API
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
temperature=0.3
)
# Extract the response content
content = response.choices[0].message.content.strip()
vignette = content
tone = desired_tone
return vignette, tone
# Function to generate internal-external options
def generate_internal_external_options(chat_history, vignette, user_state):
prompt = f"""
Based on the following scenario:
"{vignette}"
Provide two possible causes for why this situation occurred, focusing on **internal** and **external** factors that are directly related to the scenario.
Ensure each explanation is **concise** and captures the essence of an internal or external cause, without excessive detail. The causes should be easy for the user to understand, without overwhelming them with too many specifics.
Describe these explanations from the user's point of view, making them relatable and personal.
Present the options in the following format exactly:
A: [Specific internal reason]
B: [Specific external reason]
Do not include any additional text or explanation.
Use simple, but neutral and professional language suitable for a psychological assessment.
"""
try:
response = openai.chat.completions.create(
model="gpt-4o-mini",
temperature=0.3,
messages=[
{"role": "system", "content": "You are assisting in generating attribution options based on a given scenario for a psychological assessment. Directly address the user. Present a single brief sentence for each option."},
{"role": "user", "content": prompt},
],
)
content = response.choices[0].message.content.strip()
print(f"Raw internal_external_options response: {content}") # Logging
# Split the response into lines
lines = content.split('\n')
# Filter lines that start with "A:" or "B:"
options = [line.strip() for line in lines if line.strip().startswith(("A:", "B:"))]
# If more than 2 options are present, trim the list to the first two
if len(options) > 2:
options = options[:2]
# If fewer than 2 options are present, handle accordingly (e.g., add placeholders)
while len(options) < 2:
options.append("Option missing due to system error.")
# Join the options into a single string separated by newlines
options_text = "\n".join(options)
return options_text
except Exception as e:
print(f"Error generating internal_external options: {e}")
return "Option missing due to system error.\nOption missing due to system error."
# Function to generate stable-unstable and global-specific options
def generate_stable_unstable_options(vignette, previous_choice, user_state):
"""
Generates exactly two short statements explaining what might have led to a situation.
Ensures only lines starting with "A:" or "B:" are returned.
"""
# Determine the attribution type based on the user's previous choice
if previous_choice == '1':
attribution_type = 'Internal'
elif previous_choice == '2':
attribution_type = 'External'
else:
attribution_type = 'Internal' # Default to Internal if unexpected input
prompt = f"""
Generate exactly two short statements explaining what might have led to this situation, each on its own line.
They must strictly reflect a {attribution_type.lower()} cause, with no references to outside factors if {attribution_type.lower()} is "internal,"
and no references to personal traits if {attribution_type.lower()} is "external."
1) Provide a stable explanation
2) Provide a more temporary or unstable explanation
Instructions:
- Phrase all statements in second person.
- Do not mention external influences if you're generating an internal cause.
- Do not mention internal traits if you're generating an external cause.
- Do not label the options as stable/unstable/etc. in the text itself.
- Start each line with "A:" or "B:" only.
- Keep the language simple, pragmatic, and relevant to the scenario:
"{vignette}"
- Each statement should be concise, neutral, and easy to understand, without extra commentary.
- Do not include disclaimers, personal info, or text beyond the four statements.
"""
messages = [
{"role": "system", "content": "You are a strict output assistant. Produce only the specified lines."},
{"role": "user", "content": prompt},
]
# Append formatted chat history if necessary
# formatted_history = []
# for user_msg, assistant_msg in chat_history:
# if user_msg:
# formatted_history.append({"role": "user", "content": user_msg})
# if assistant_msg:
# formatted_history.append({"role": "assistant", "content": assistant_msg})
# messages += formatted_history
try:
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
temperature=0.3,
max_tokens=300
)
content = response.choices[0].message.content.strip()
print("stable_unstable options before line split:")
print(content)
# Split the response into lines
lines = content.split('\n')
# Filter lines that start with "A:" or "B:"
options = [line.strip() for line in lines if line.strip().startswith(("A:", "B:"))]
print("stable_unstable options after A/B filter:")
print(options)
# If more than 2 options are present, trim the list to the first two
if len(options) > 2:
options = options[:2]
# If fewer than 2 options are present, handle accordingly (e.g., add placeholders)
while len(options) < 2:
options.append("Option missing due to system error.")
# Join the options into a single string separated by newlines
options_text = "\n".join(options)
return options_text
except Exception as e:
print(f"Error generating options: {e}")
return "Error generating options. Please try again."
def generate_global_specific_options(vignette, previous_choice, user_state):
"""
Generates exactly two short statements explaining what might have led to a situation.
Ensures only lines starting with "A:" or "B:" are returned.
"""
# Determine the attribution type based on the user's previous choice
if previous_choice == '1':
attribution_type = 'Internal'
elif previous_choice == '2':
attribution_type = 'External'
else:
attribution_type = 'Internal' # Default to Internal if unexpected input
prompt = f"""
Generate exactly two short statements explaining what might have led to this situation, each on its own line, with no additional commentary. They must strictly reflect a {attribution_type.lower()} cause.
- If {attribution_type.lower()} is "internal," do not reference any outside factors such as environment, other people, or external circumstances.
- If {attribution_type.lower()} is "external," do not reference personal traits, inherent aptitudes, or individual qualities.
Focus on these two points:
1) A broader/global explanation that applies widely.
2) A more situation-specific explanation.
Instructions:
- Phrase all statements in second person.
- Start each line with "A:" or "B:" only, and provide no other lines.
- Keep the language simple, neutral, and directly relevant to:
"{vignette}"
- Each statement should be concise and easy to understand, with no disclaimers or extra text.
- Output only those two lines, nothing else.
"""
messages = [
{"role": "system", "content": "You are a strict output assistant. Produce only the specified lines."},
{"role": "user", "content": prompt},
]
# # Append formatted chat history if necessary
# formatted_history = []
# for user_msg, assistant_msg in chat_history:
# if user_msg:
# formatted_history.append({"role": "user", "content": user_msg})
# if assistant_msg:
# formatted_history.append({"role": "assistant", "content": assistant_msg})
# messages += formatted_history
try:
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
temperature=0.3,
max_tokens=300
)
content = response.choices[0].message.content.strip()
print("global_specific options before line split:")
print(content)
# Split the response into lines
lines = content.split('\n')
# Filter lines that start with "A:" or "B:"
options = [line.strip() for line in lines if line.strip().startswith(("A:", "B:"))]
print("global_specific options after A/B filter:")
print(options)
# If more than 2 options are present, trim the list to the first two
if len(options) > 2:
options = options[:2]
# If fewer than 2 options are present, handle accordingly (e.g., add placeholders)
while len(options) < 2:
options.append("Option missing due to system error.")
# Join the options into a single string separated by newlines
options_text = "\n".join(options)
return options_text
except Exception as e:
print(f"Error generating options: {e}")
return "Error generating options. Please try again."
# First reveal
def generate_first_reveal(vignette, user_state):
prompt = f"""
Based on the following scenario:
"{vignette}"
Present a first reveal that adds complexity to the situation. The reveal should provide new information that challenges the user's previous attributions.
Use neutral and professional language suitable for a psychological assessment.
Keep the reveal concise.
Only provide the vignette text and do not include phrases like "Sure", "Here is your vignette", or any other extra text.
"""
response = openai.chat.completions.create(
model="gpt-4o-mini",
temperature=0.3,
messages=[
{"role": "system", "content": "You are assisting in generating attribution options based on a given scenario for a psychological assessment. Directly address the user. Present a single brief sentence for eacht option."},
{"role": "user", "content": prompt},
],
)
return response.choices[0].message.content.strip()
# Second reveal
def generate_second_reveal(vignette, first_reveal):
prompt = f"""
Based on the following scenario:
"{vignette}"
And the first reveal:
"{first_reveal}"
Present a second reveal that significantly alters the user's interpretation of the situation. The reveal should provide additional context or details that prompt a re-evaluation of the initial attribution.
Use neutral and professional language suitable for a psychological assessment.
Keep the reveal concise.
Only provide the vignette text and do not include phrases like "Sure", "Here is your vignette", or any other extra text.
"""
response = openai.chat.completions.create(
model="gpt-4o-mini",
temperature=0.3,
messages=[
{"role": "system", "content": "You are assisting in generating attribution options based on a given scenario for a psychological assessment. Directly address the user. Present a single brief sentence for eacht option."},
{"role": "user", "content": prompt},
],
)
return response.choices[0].message.content.strip()
# Save to Excel
def save_data_to_excel(data):
# Read the existing Excel file
df = pd.read_excel('assessment_data.xlsx')
# Convert the data dictionary to a DataFrame
new_entry = pd.DataFrame([data])
# Append the new entry to the DataFrame
df = pd.concat([df, new_entry], ignore_index=True)
# Save the updated DataFrame back to the Excel file
df.to_excel('assessment_data.xlsx', index=False)
# Excel for control condition
def save_data_to_control_excel(data):
# Read the existing Excel file
df = pd.read_excel('assessment_data_nonpersonal.xlsx')
# Convert the data dictionary to a DataFrame
new_entry = pd.DataFrame([data])
# Append the new entry to the DataFrame
df = pd.concat([df, new_entry], ignore_index=True)
# Save the updated DataFrame back to the Excel file
df.to_excel('assessment_data_nonpersonal.xlsx', index=False)
# Save to Pickle
def save_data_to_pickle(data):
# Read the existing Excel file
df = pd.read_pickle(pickle_file)
# Convert the data dictionary to a DataFrame
new_entry = pd.DataFrame([data])
# Append the new entry to the DataFrame
df = pd.concat([df, new_entry], ignore_index=True)
# Save the updated DataFrame back to the Excel file
df.to_pickle(pickle_file)
# Pickle for control condition
def save_data_to_control_pickle(data):
# Read the existing Excel file
df = pd.read_pickle(pickle_file2)
# Convert the data dictionary to a DataFrame
new_entry = pd.DataFrame([data])
# Append the new entry to the DataFrame
df = pd.concat([df, new_entry], ignore_index=True)
# Save the updated DataFrame back to the Excel file
df.to_pickle(pickle_file2)
def chat(fn_print, fn_input):
print("test")
conversation_history = []
user_responses = [] # List to store raw user responses
standardized_data = {} # Dictionary to store standardized data for the Excel file
stage = "start"
user_id = str(uuid.uuid4()) # Generate a unique user ID
topic_choice = None
vignette_tones = ['Positive', 'Negative', 'Negative', 'Positive'] # Two positive and two negative
vignette_counter = 1 # To keep track of the current vignette number
while True:
if stage == "start":
fn_print("Welcome! Before we begin, please note that your responses will be used for research purposes. Your data will be kept confidential and anonymous.")
options_text = "Yes\nNo"
while True:
user_input = fn_input("Do you consent to participate? (yes/no): ")
user_responses.append({'stage': 'consent', 'response': user_input})
conversation_history.append({"role": "user", "content": user_input})
mapped_option = interpret_response(user_input, options_text)
if mapped_option == '1' or user_input.strip().lower() in ['yes', 'y']:
standardized_data['Consent'] = 'Yes'
stage = "user_profile"
break
elif mapped_option == '2' or user_input.strip().lower() in ['no', 'n']:
standardized_data['Consent'] = 'No'
fn_print("Thank you for your time. Goodbye!")
return conversation_history, user_responses # Exit the chat
else:
fn_print("Sorry, I couldn't understand your response. Please answer 'yes' or 'no'.")
stage = "user_profile"
elif stage == "user_profile":
fn_print("""Great! During the course of this assessment you will be confronted with descriptions of fictional everyday situations. Please try to immerse yourself in these scenarios as if they were happening to you personally.
In order to provide you with situations that might be more relevant to you specifically,
we need some general information about you. Don't worry, you will remain anonymous!
Please tell us your age, profession and one of your personal interests.""")
user_profile_response = fn_input("You: ")
user_responses.append({'stage': 'user_profile', 'response': user_profile_response})
conversation_history.append({"role": "user", "content": user_profile_response})
standardized_data['Age'] = standardize_response("Please extract the user's age from the following input.", user_profile_response)
standardized_data['Profession'] = standardize_response("Please extract the user's profession from the following input.", user_profile_response)
standardized_data['Interests'] = standardize_response("Please extract the user's interests from the following input.", user_profile_response)
stage = "topic_choice"
elif stage == "topic_choice":
fn_print("Let's create a scenario for you.")
fn_print("Which topic would you prefer?")
fn_print("1. A situation related to your profession.")
fn_print("2. A situation related to your personal interests.")
options_text = "1. A situation related to your profession.\n2. A situation related to your personal interests."
while True:
user_input = fn_input("You: ")
user_responses.append({'stage': 'topic_choice', 'response': user_input})
conversation_history.append({"role": "user", "content": user_input})
mapped_option = interpret_response(user_input, options_text)
if mapped_option in ['1', '2']:
topic_choice_response = mapped_option
standardized_data['Topic Choice'] = topic_choice_response
topic_choice = topic_choice_response
stage = "vignette"
break
else:
fn_print("Sorry, I couldn't understand your response. Could you please specify your choice?")
elif stage == "vignette":
if vignette_counter > 4:
# All vignettes have been presented
fn_print("You have completed all scenarios. Thank you for your participation! You will now be redirected to Prolific. Please don't close the browser yet. Goodbye!")
save_data_to_excel(standardized_data)
fn_print(f"Total vignettes presented: {vignette_counter - 1}")
break
# Determine the desired tone for the current vignette
desired_tone = vignette_tones[vignette_counter - 1]
vignette, tone = generate_vignette(conversation_history, topic_choice, desired_tone)
if vignette is None:
fn_print("There was an error generating the vignette. Exiting the assessment.")
break
fn_print("Alright, please imagine you are witnessing the following scene:")
fn_print(f"Chatbot: {vignette}")
conversation_history.append({"role": "assistant", "content": vignette})
user_responses.append({'stage': 'vignette', 'content': vignette, 'tone': tone})
# Temporarily store the vignette and tone with a unique key per vignette
standardized_data[f'Vignette{vignette_counter}'] = vignette
standardized_data[f'Tone{vignette_counter}'] = tone
stage = "vignette_usability_assessment"
elif stage == "vignette_usability_assessment":
fn_print(f"Vignette {vignette_counter} Usability Assessment:")
fn_print("On a scale from 1 to 10, how relevant, immersive, or relatable is the depicted scenario to you personally? (1 = not at all, 10 = completely)")
relevance_rating = fn_input("You: ")
user_responses.append({'stage': 'vignette_usability_assessment', 'response': relevance_rating})
conversation_history.append({"role": "user", "content": relevance_rating})
# Store the initial relevance rating if not already stored
if f'Initial Relevance Rating{vignette_counter}' not in standardized_data:
standardized_data[f'Initial Relevance Rating{vignette_counter}'] = int(relevance_rating)
if int(relevance_rating) >= 7:
# Accept the vignette
standardized_data[f'Vignette{vignette_counter}'] = vignette
standardized_data[f'Tone{vignette_counter}'] = tone
# Store the final relevance rating
standardized_data[f'Final Relevance Rating{vignette_counter}'] = int(relevance_rating)
stage = "internal_external"
else:
# Ask for further clarification
fn_print("I'm sorry to hear that the scenario wasn't quite fitting. Could you please provide more details about your specific context, so we can come up with a better one?")
additional_info = fn_input("You: ")
user_responses.append({'stage': 'additional_info', 'response': additional_info})
conversation_history.append({"role": "user", "content": additional_info})
# Use the additional info to regenerate the vignette
stage = "vignette_regeneration"
elif stage == "vignette_regeneration":
# Use the additional info in the conversation history to regenerate the vignette
vignette, tone = generate_vignette(conversation_history, topic_choice, desired_tone)
fn_print("Okay, let's try again. Please imagine you are witnessing the following scene:")
fn_print(f"Chatbot: {vignette}")
conversation_history.append({"role": "assistant", "content": vignette})
user_responses.append({'stage': 'vignette_regenerated', 'content': vignette, 'tone': tone})
# Temporarily store the new vignette and tone
standardized_data[f'Vignette{vignette_counter}'] = vignette
standardized_data[f'Tone{vignette_counter}'] = tone
# Go back to usability assessment
stage = "vignette_usability_assessment"
elif stage == "internal_external":
options_text = generate_internal_external_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'])
fn_print("Based on the scenario above, which of the following explanations do you think is most likely?:")
fn_print(f"Options:\n{options_text}")
while True:
user_input = fn_input("Your explanation: ")
user_responses.append({'stage': 'internal_external', 'options': options_text, 'response': user_input})
conversation_history.append({"role": "user", "content": user_input})
mapped_option = interpret_response(user_input, options_text)
if mapped_option in ['1', '2']:
explanation_response = mapped_option
break
else:
fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
# Store the initial internal/external attribution numerically
if explanation_response == '1':
standardized_data[f'Initial Internal{vignette_counter}'] = 1
standardized_data[f'Initial External{vignette_counter}'] = 0
elif explanation_response == '2':
standardized_data[f'Initial Internal{vignette_counter}'] = 0
standardized_data[f'Initial External{vignette_counter}'] = 1
else:
standardized_data[f'Initial Internal{vignette_counter}'] = None
standardized_data[f'Initial External{vignette_counter}'] = None
stage = "stable_unstable_global_specific"
elif stage == "stable_unstable_global_specific":
previous_choice = explanation_response
options_text = generate_stable_unstable_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'], previous_choice)
fn_print("Now, considering your previous choice, please select which option best explains the situation:")
fn_print(f"Options:\n{options_text}")
while True:
user_input = fn_input("Your explanation: ")
user_responses.append({'stage': 'stable_unstable_global_specific', 'options': options_text, 'response': user_input})
conversation_history.append({"role": "user", "content": user_input})
mapped_option = interpret_response(user_input, options_text)
if mapped_option in ['1', '2', '3', '4']:
explanation_stable_unstable_response = mapped_option
break
else:
fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
# Store the initial stable/unstable and global/specific attributions numerically
if explanation_stable_unstable_response == '1':
standardized_data[f'Initial Stable{vignette_counter}'] = 1
standardized_data[f'Initial Unstable{vignette_counter}'] = 0
standardized_data[f'Initial Global{vignette_counter}'] = 1
standardized_data[f'Initial Specific{vignette_counter}'] = 0
elif explanation_stable_unstable_response == '2':
standardized_data[f'Initial Stable{vignette_counter}'] = 1
standardized_data[f'Initial Unstable{vignette_counter}'] = 0
standardized_data[f'Initial Global{vignette_counter}'] = 0
standardized_data[f'Initial Specific{vignette_counter}'] = 1
elif explanation_stable_unstable_response == '3':
standardized_data[f'Initial Stable{vignette_counter}'] = 0
standardized_data[f'Initial Unstable{vignette_counter}'] = 1
standardized_data[f'Initial Global{vignette_counter}'] = 1
standardized_data[f'Initial Specific{vignette_counter}'] = 0
elif explanation_stable_unstable_response == '4':
standardized_data[f'Initial Stable{vignette_counter}'] = 0
standardized_data[f'Initial Unstable{vignette_counter}'] = 1
standardized_data[f'Initial Global{vignette_counter}'] = 0
standardized_data[f'Initial Specific{vignette_counter}'] = 1
else:
standardized_data[f'Initial Stable{vignette_counter}'] = None
standardized_data[f'Initial Unstable{vignette_counter}'] = None
standardized_data[f'Initial Global{vignette_counter}'] = None
standardized_data[f'Initial Specific{vignette_counter}'] = None
stage = "first_reveal"
elif stage == "first_reveal":
first_reveal = generate_first_reveal(vignette)
fn_print("Alright, noted. Now, please imagine the following:")
fn_print(f"Chatbot: {first_reveal}")
conversation_history.append({"role": "assistant", "content": first_reveal})
user_responses.append({'stage': 'first_reveal', 'content': first_reveal})
standardized_data[f'First Reveal{vignette_counter}'] = first_reveal
stage = "internal_external_reassessment"
elif stage == "internal_external_reassessment":
options_text = generate_internal_external_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'])
fn_print("Considering these new developments, please select which of these options seems more likely to you:")
fn_print(f"Options:\n{options_text}")
while True:
user_input = fn_input("Your explanation: ")
user_responses.append({'stage': 'internal_external_reassessment', 'options': options_text, 'response': user_input})
conversation_history.append({"role": "user", "content": user_input})
mapped_option = interpret_response(user_input, options_text)
if mapped_option in ['1', '2']:
assessment_internal_external_response = mapped_option
break
else:
fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
# Store the reassessment internal/external attribution numerically
if assessment_internal_external_response == '1':
standardized_data[f'Reassessment Internal{vignette_counter}'] = 1
standardized_data[f'Reassessment External{vignette_counter}'] = 0
elif assessment_internal_external_response == '2':
standardized_data[f'Reassessment Internal{vignette_counter}'] = 0
standardized_data[f'Reassessment External{vignette_counter}'] = 1
else:
standardized_data[f'Reassessment Internal{vignette_counter}'] = None
standardized_data[f'Reassessment External{vignette_counter}'] = None
stage = "stable_unstable_global_specific_reassessment"
elif stage == "stable_unstable_global_specific_reassessment":
previous_choice = assessment_internal_external_response
options_text = generate_stable_unstable_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'], previous_choice)
fn_print("Now, based on your previous choice, once again select, which option best explains the situation:")
fn_print(f"Options:\n{options_text}")
while True:
user_input = fn_input("Your explanation: ")
user_responses.append({'stage': 'stable_unstable_global_specific_reassessment', 'options': options_text, 'response': user_input})
conversation_history.append({"role": "user", "content": user_input})
mapped_option = interpret_response(user_input, options_text)
if mapped_option in ['1', '2', '3', '4']:
assessment_stable_unstable_response = mapped_option
break
else:
fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
# Store the reassessment stable/unstable and global/specific attributions numerically
if assessment_stable_unstable_response == '1':
standardized_data[f'Reassessment Stable{vignette_counter}'] = 1
standardized_data[f'Reassessment Unstable{vignette_counter}'] = 0
standardized_data[f'Reassessment Global{vignette_counter}'] = 1
standardized_data[f'Reassessment Specific{vignette_counter}'] = 0
elif assessment_stable_unstable_response == '2':
standardized_data[f'Reassessment Stable{vignette_counter}'] = 1
standardized_data[f'Reassessment Unstable{vignette_counter}'] = 0
standardized_data[f'Reassessment Global{vignette_counter}'] = 0
standardized_data[f'Reassessment Specific{vignette_counter}'] = 1
elif assessment_stable_unstable_response == '3':
standardized_data[f'Reassessment Stable{vignette_counter}'] = 0
standardized_data[f'Reassessment Unstable{vignette_counter}'] = 1
standardized_data[f'Reassessment Global{vignette_counter}'] = 1
standardized_data[f'Reassessment Specific{vignette_counter}'] = 0
elif assessment_stable_unstable_response == '4':
standardized_data[f'Reassessment Stable{vignette_counter}'] = 0
standardized_data[f'Reassessment Unstable{vignette_counter}'] = 1
standardized_data[f'Reassessment Global{vignette_counter}'] = 0
standardized_data[f'Reassessment Specific{vignette_counter}'] = 1
else:
standardized_data[f'Reassessment Stable{vignette_counter}'] = None
standardized_data[f'Reassessment Unstable{vignette_counter}'] = None
standardized_data[f'Reassessment Global{vignette_counter}'] = None
standardized_data[f'Reassessment Specific{vignette_counter}'] = None
stage = "second_reveal"
elif stage == "second_reveal":
second_reveal = generate_second_reveal(vignette, first_reveal)
fn_print("Okay. Finally, please imagine this:")
fn_print(f"Chatbot: {second_reveal}")
conversation_history.append({"role": "assistant", "content": second_reveal})
user_responses.append({'stage': 'second_reveal', 'content': second_reveal})
standardized_data[f'Second Reveal{vignette_counter}'] = second_reveal
stage = "evolved_internal_external"
elif stage == "evolved_internal_external":
options_text = generate_internal_external_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'] + " " + standardized_data[f'Second Reveal{vignette_counter}'])
fn_print("With the new information, what do you think why the situation occurred:")
fn_print(f"Options:\n{options_text}")
while True:
user_input = fn_input("Your explanation: ")
user_responses.append({'stage': 'evolved_internal_external', 'options': options_text, 'response': user_input})
conversation_history.append({"role": "user", "content": user_input})
mapped_option = interpret_response(user_input, options_text)
if mapped_option in ['1', '2']:
evolved_internal_external_response = mapped_option
break
else:
fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
# Store the final internal/external attribution numerically
if evolved_internal_external_response == '1':
standardized_data[f'Final Internal{vignette_counter}'] = 1
standardized_data[f'Final External{vignette_counter}'] = 0
elif evolved_internal_external_response == '2':
standardized_data[f'Final Internal{vignette_counter}'] = 0
standardized_data[f'Final External{vignette_counter}'] = 1
else:
standardized_data[f'Final Internal{vignette_counter}'] = None
standardized_data[f'Final External{vignette_counter}'] = None
stage = "evolved_stable_unstable_global_specific"
elif stage == "evolved_stable_unstable_global_specific":
previous_choice = evolved_internal_external_response
options_text = generate_stable_unstable_options(conversation_history, standardized_data[f'Vignette{vignette_counter}'] + " " + standardized_data[f'First Reveal{vignette_counter}'] + " " + standardized_data[f'Second Reveal{vignette_counter}'], previous_choice)
fn_print("One last time, based on your previous choice, which option best explains the situation:")
fn_print(f"Options:\n{options_text}")
while True:
user_input = fn_input("Your explanation: ")
user_responses.append({'stage': 'evolved_stable_unstable_global_specific', 'options': options_text, 'response': user_input})
conversation_history.append({"role": "user", "content": user_input})
mapped_option = interpret_response(user_input, options_text)
if mapped_option in ['1', '2', '3', '4']:
evolved_stable_unstable_response = mapped_option
break
else:
fn_print("Sorry, I couldn't understand your response. Could you please rephrase or specify your choice?")
# Store the final stable/unstable and global/specific attributions numerically
if evolved_stable_unstable_response == '1':
standardized_data[f'Final Stable{vignette_counter}'] = 1
standardized_data[f'Final Unstable{vignette_counter}'] = 0
standardized_data[f'Final Global{vignette_counter}'] = 1
standardized_data[f'Final Specific{vignette_counter}'] = 0
elif evolved_stable_unstable_response == '2':
standardized_data[f'Final Stable{vignette_counter}'] = 1
standardized_data[f'Final Unstable{vignette_counter}'] = 0
standardized_data[f'Final Global{vignette_counter}'] = 0
standardized_data[f'Final Specific{vignette_counter}'] = 1
elif evolved_stable_unstable_response == '3':
standardized_data[f'Final Stable{vignette_counter}'] = 0
standardized_data[f'Final Unstable{vignette_counter}'] = 1
standardized_data[f'Final Global{vignette_counter}'] = 1
standardized_data[f'Final Specific{vignette_counter}'] = 0
elif evolved_stable_unstable_response == '4':
standardized_data[f'Final Stable{vignette_counter}'] = 0
standardized_data[f'Final Unstable{vignette_counter}'] = 1
standardized_data[f'Final Global{vignette_counter}'] = 0
standardized_data[f'Final Specific{vignette_counter}'] = 1
else:
standardized_data[f'Final Stable{vignette_counter}'] = None
standardized_data[f'Final Unstable{vignette_counter}'] = None
standardized_data[f'Final Global{vignette_counter}'] = None
standardized_data[f'Final Specific{vignette_counter}'] = None
stage = "likelihood_of_change"
elif stage == "likelihood_of_change":
fn_print("Think back to your initial interpretation of the scene. On a scale from 1 to 10, how likely are you to change that initial interpretation after receiving the new information? (1 = least likely, 10 = most likely)")
user_input = fn_input("You: ")
user_responses.append({'stage': 'likelihood_of_change', 'response': user_input})
conversation_history.append({"role": "user", "content": user_input})
# Interpret the user's response to extract the numerical rating
prompt = f"""
The user was asked to rate their likelihood of changing their initial interpretation on a scale from 1 to 10.
The user responded: "{user_input}"
Extract the numerical rating from the user's response. Provide the number only.
If you cannot determine the rating, respond with "Unable to determine".
"""
response = openai.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
temperature=0.0,
max_tokens=5
)
assistant_response = response.choices[0].message.content.strip()
if assistant_response.isdigit() and 1 <= int(assistant_response) <= 10:
standardized_data[f'Likelihood of Change{vignette_counter}'] = int(assistant_response)
stage = "subsequent_vignettes"
else:
fn_print("Sorry, I couldn't understand your response. Please provide a number between 1 and 10.")
elif stage == "subsequent_vignettes":
fn_print("Thank you! We are now finished with this scene. In total you will be seeing four scenes.")
vignette_counter += 1 # Move to the next vignette
stage = "topic_choice" # Reset stage to process the next vignette
return conversation_history, user_responses
import os
import openai
import random
import pandas as pd
import uuid
import pickle
# Module seeds
context_types = {
"Work/Professional": [
"Working on a project or task",
"Attending a meeting or briefing",
"Collaborating with colleagues or team members",
"Presenting a proposal or idea",
"Responding to client or customer feedback",
"Managing or resolving a workplace conflict",
"Negotiating a contract or agreement",
"Performing routine tasks",
"Handling unexpected challenges"
],
"Social": [
"Engaging in a social gathering or event",
"Having a one-on-one conversation with a friend or acquaintance",
"Participating in a group activity or hobby",
"Sharing ideas or opinions in a casual discussion",
"Dealing with a social conflict or disagreement",
"Networking at a professional or social event"
],
"Physical Activity": [
"Participating in a team sport or physical competition",
"Engaging in an outdoor activity",
"Training or practicing with a coach or instructor",
"Competing in a tournament or race",
"Engaging in a personal fitness routine or challenge",
"Performing a physical task that requires coordination or teamwork"
],
"Reflection": [
"Reflecting on a past decision or action",
"Planning future goals or strategies",
"Evaluating personal or professional progress",
"Contemplating a challenging situation or conflict",
"Revisiting a difficult conversation or interaction",
"Assessing personal strengths, weaknesses, or skills"
],
"Educational": [
"Participating in a class, lecture, or seminar",
"Collaborating on a study project or research",
"Receiving feedback from a teacher or mentor",
"Preparing for or taking an exam",
"Engaging in group study or discussion",
"Presenting academic work or research findings"
],
"Creative": [
"Working on a creative project",
"Collaborating with others on a creative endeavor",
"Receiving feedback on a creative piece",
"Presenting a creative work to an audience",
"Brainstorming or ideating new concepts",
"Experimenting with new techniques or styles"
]
}
interaction_types = {
"Authority Feedback": [
"Receiving feedback or critique from a supervisor, boss, or mentor",
"Listening to advice or guidance from a coach or teacher",
"Engaging in a performance review or evaluation",
"Responding to managerial decisions or directives"
],
"Peer Reaction": [
"Receiving input, advice, or reactions from a colleague, friend, or teammate",
"Discussing ideas or opinions with peers in a group setting",
"Addressing concerns, compliments, or criticisms from a peer",
"Collaborating on a task or project with equal responsibility"
],
"Group Dynamics": [
"Participating in a group discussion or brainstorming session",
"Leading or following in a team activity or project",
"Managing group feedback or collective opinions",
"Navigating differing opinions, conflicts, or agreements within a group"
],
"Self-Reflection": [
"Analyzing personal decisions, actions, or behaviors",
"Contemplating improvements or changes based on past experiences",
"Reflecting on feedback received from others",
"Re-evaluating personal goals, priorities, or values"
],
"Creative Feedback": [
"Seeking opinions or critiques on a creative project from peers or mentors",
"Engaging in a discussion about a creative piece's direction or style",
"Presenting creative work to a group and receiving diverse reactions"
],
"Social Participation": [
"Engaging in a group activity or event related to a hobby or interest",
"Discussing or sharing personal achievements or interests in a social setting",
"Navigating group dynamics during a leisure activity or social gathering"
]
}