File size: 9,774 Bytes
4c59e23
 
e5d7edb
4c59e23
 
 
 
 
 
 
 
e5d7edb
 
4c59e23
 
 
e5d7edb
 
4c59e23
e5d7edb
 
 
 
4c59e23
e5d7edb
4c59e23
 
6bacb5e
e5d7edb
 
 
6bacb5e
e5d7edb
 
4c59e23
e5d7edb
 
 
4c59e23
e5d7edb
 
 
 
4c59e23
e5d7edb
 
4c59e23
e5d7edb
4c59e23
e5d7edb
 
 
 
4c59e23
e5d7edb
4c59e23
e5d7edb
 
 
4c59e23
e5d7edb
 
 
 
 
4c59e23
e5d7edb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c59e23
e5d7edb
4c59e23
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import os
import streamlit as st
# from anthropic import Anthropic
import openai # Added OpenAI import
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configure Streamlit page settings
st.set_page_config(
    page_title="Attachment Style Roleplay Simulator",
    page_icon="🎭",
    layout="centered",
)

# Initialize OpenAI client
# anthropic = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY") or os.getenv("ANTHROPIC_KEY"))
try:
    client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")) # Use OpenAI client
    if not client.api_key:
        st.error("OpenAI API Key not found. Please set the OPENAI_API_KEY environment variable.")
        st.stop()
except Exception as e:
    st.error(f"Failed to configure OpenAI client: {e}")
    st.stop()


# Initialize session state for form inputs if not present
if "setup_complete" not in st.session_state:
    st.session_state.setup_complete = False

if "messages" not in st.session_state:
    st.session_state.messages = []

# Main page header
st.markdown("<h1 style='text-align: center; color: #333;'>Attachment Style Roleplay Simulator</h1>", unsafe_allow_html=True)
st.markdown("<p style='text-align: center; font-size: 18px; color: #555; margin-bottom: 1em;'>A Safe Space for Practicing Difficult Conversations</p>", unsafe_allow_html=True)

# Welcome text and instructions
if not st.session_state.setup_complete:
    st.markdown("""
    ## Practice Hard Conversations—Safely.

    Welcome to a therapeutic roleplay simulator built for emotionally charged moments.
    This tool helps you rehearse boundary-setting and difficult conversations by simulating realistic relational dynamics—tailored to your attachment style.

    You'll choose:

    - A scenario (e.g., "Ask my mom not to comment on my body")
    - A tone of response (e.g., supportive, guilt-tripping, dismissive)
    - Your attachment style (e.g., anxious, avoidant, disorganized)
    - And your goal (e.g., "I want to stay calm and not backtrack")

    The AI will take on the role of a realistic human responder—not to therapize you, but to mirror the relational pressure you might encounter in real life. Then, you'll get a reflection summary to help you track your emotional patterns and practice courage.

    ### 🧠 Not sure what your attachment style is?
    You can take this [free quiz from Sarah Peyton](https://www.yourresonantself.com/attachment-assessment) to learn more.
    Or you can just pick the one that vibes when you read it:

    - **Anxious** – "I often worry if I've upset people or said too much."
    - **Avoidant** – "I'd rather handle things alone than depend on others."
    - **Disorganized** – "I want closeness, but I also feel overwhelmed or mistrusting."
    - **Secure** – "I can handle conflict and connection without losing myself."
    """)

# Sidebar with setup form
with st.sidebar:
    st.markdown("""
    ### Welcome! 👋

    Hi, I'm Jocelyn Skillman, LMHC — a clinical therapist, relational design ethicist, and creator of experimental tools that explore how AI can support (not replace) human care.

    Each tool in this collection is thoughtfully designed to:

    - Extend therapeutic support between sessions
    - Model emotional safety and relational depth
    - Help clients and clinicians rehearse courage, regulation, and repair
    - Stay grounded in trauma-informed, developmentally sensitive frameworks

    I use powerful language models like OpenAI's GPT-4o for these tools, chosen for their ability to simulate nuanced human interaction and responsiveness to emotionally complex prompts.

    As a practicing therapist, I imagine these resources being especially helpful to clinicians like myself — companions in the work of tending to others with insight, warmth, and care.

    #### Connect With Me
    🌐 [jocelynskillman.com](http://www.jocelynskillman.com)
    📬 [Substack: Relational Code](https://jocelynskillmanlmhc.substack.com/)

    ---
    """)

    st.markdown("### 🎯 Simulation Setup")

    with st.form("simulation_setup"):
        attachment_style = st.selectbox(
            "Your Attachment Style",
            ["Anxious", "Avoidant", "Disorganized", "Secure"],
            help="Select your attachment style for this practice session"
        )

        scenario = st.text_area(
            "Scenario Description",
            placeholder="Example: I want to tell my dad I can't call every night anymore.",
            help="Describe the conversation you want to practice"
        )

        tone = st.text_input(
            "Desired Tone for AI Response",
            placeholder="Example: guilt-tripping, dismissive, supportive",
            help="How should the AI character respond?"
        )

        practice_goal = st.text_area(
            "Your Practice Goal",
            placeholder="Example: staying grounded and not over-explaining",
            help="What would you like to work on in this conversation?"
        )

        submit_setup = st.form_submit_button("Start Simulation")

        if submit_setup and scenario and tone and practice_goal:
            # Create system message with simulation parameters
            system_message_content = f"""You are an AI roleplay partner simulating a conversation. Maintain the requested tone throughout. Keep responses concise (under 3 lines) unless asked to elaborate. Do not break character unless the user types 'pause', 'reflect', or 'debrief'.

User's Attachment Style: {attachment_style}
Scenario: {scenario}
Your Tone: {tone}
User's Goal: {practice_goal}

Begin the simulation based on the scenario."""

            # Store the system message and initial assistant message
            # OpenAI expects the system message as the first message in the list
            st.session_state.messages = [
                {"role": "system", "content": system_message_content},
                {"role": "assistant", "content": "Simulation ready. You can begin the conversation whenever you're ready."}
            ]
            st.session_state.setup_complete = True
            # No need to store system_message separately in session state anymore
            # if "system_message" in st.session_state:
            #      del st.session_state["system_message"]
            st.rerun()


# Display simulation status
if not st.session_state.setup_complete:
    st.info("👈 Please complete the simulation setup in the sidebar to begin.")
else:
    # Display chat history
    # Filter out system message for display purposes
    display_messages = [m for m in st.session_state.messages if m.get("role") != "system"]
    for message in display_messages:
        # Ensure role is valid before creating chat message
        role = message.get("role")
        if role in ["user", "assistant"]:
             with st.chat_message(role):
                 st.markdown(message["content"])
        # else: # Optional: Log or handle unexpected roles
        #    print(f"Skipping display for message with role: {role}")

    # User input field
    if user_prompt := st.chat_input("Type your message here... (or type 'debrief' to end simulation)"):
        # Add user message to chat history
        st.session_state.messages.append({"role": "user", "content": user_prompt})

        # Display user message
        with st.chat_message("user"):
            st.markdown(user_prompt)

        # Prepare messages for API call (already includes system message as the first item)
        api_messages = st.session_state.messages

        # Get OpenAI's response
        with st.spinner("..."):
            try:
                # Replace Anthropic call with OpenAI call
                # response = anthropic.messages.create(
                #     model="claude-3-opus-20240229",
                #     max_tokens=1024,
                #     messages=api_messages
                # )
                # assistant_response = response.content[0].text

                response = client.chat.completions.create(
                    model="gpt-4o", # Use gpt-4o
                    messages=api_messages, # Pass the whole conversation history
                    max_tokens=150 # Keep responses relatively brief by default
                )
                assistant_response = response.choices[0].message.content


                # Add assistant response to chat history
                st.session_state.messages.append(
                    {"role": "assistant", "content": assistant_response}
                )

                # Display assistant response
                with st.chat_message("assistant"):
                    st.markdown(assistant_response)

            except Exception as e:
                st.error(f"An error occurred: {e}")
                error_message = f"Sorry, I encountered an error: {e}"
                # Add error message to chat history to inform the user
                st.session_state.messages.append({"role": "assistant", "content": error_message})
                with st.chat_message("assistant"):
                     st.markdown(error_message)
                # Avoid adding the failed user message again if an error occurs
                # We might want to remove the last user message or handle differently
                # if st.session_state.messages[-2]["role"] == "user":
                #     st.session_state.messages.pop(-2) # Example: remove user msg that caused error


# Footer
st.markdown("---")
st.markdown("<p style='text-align: center; font-size: 16px; color: #666;'>by <a href='http://www.jocelynskillman.com' target='_blank'>Jocelyn Skillman LMHC</a> - to learn more check out: <a href='https://jocelynskillmanlmhc.substack.com/' target='_blank'>jocelynskillmanlmhc.substack.com</a></p>", unsafe_allow_html=True)