Repository navigation
Expand file tree
/
Copy pathwrapper.js
More file actions
247 lines (207 loc) · 12.3 KB
/
Copy pathwrapper.js
File metadata and controls
247 lines (207 loc) · 12.3 KB
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
const OPENAI_API_URL = 'https://api.openai.com/v1/responses';
const OPENAI_MODEL = 'gpt-4.1-mini';
const BERNARD_FALLBACK_REPLY =
"I'm having trouble replying right now. Please try again in a moment.";
const MISSING_KEY_CODE = 'MISSING_OPENAI_API_KEY';
const ANSWER_LABELS = { 1: 'Disagree', 2: 'Slightly disagree', 3: 'Maybe', 4: 'Slightly agree', 5: 'Agree' };
const TRAIT_KEYS = ['happy', 'sadness', 'motivation', 'futureAnxiety', 'overthinking', 'ambition', 'aggression', 'loyalty', 'guilt', 'burnout', 'selfDoubt', 'focus'];
const QUESTION_TEXTS = [
{ category: 'Core Identity & Self-Perception', text: 'I have a clear understanding of who I am.' },
{ category: 'Core Identity & Self-Perception', text: 'I am confident in my personality and values.' },
{ category: 'Core Identity & Self-Perception', text: 'I actively try to improve myself.' },
{ category: 'Core Identity & Self-Perception', text: 'I feel uncertain about my identity.' },
{ category: 'Core Identity & Self-Perception', text: 'I have a clear vision of who I want to become.' },
{ category: 'Emotional Patterns', text: 'I feel stressed frequently.' },
{ category: 'Emotional Patterns', text: 'My mood is easily affected by external events.' },
{ category: 'Emotional Patterns', text: 'I tend to bottle up my emotions.' },
{ category: 'Emotional Patterns', text: 'I openly talk about how I feel.' },
{ category: 'Emotional Patterns', text: 'I often feel overwhelmed.' },
{ category: 'Emotional Patterns', text: 'I have healthy ways to cope with stress.' },
{ category: 'Motivation & Work Style', text: 'I stay consistent with my goals.' },
{ category: 'Motivation & Work Style', text: 'I rely on discipline rather than motivation.' },
{ category: 'Motivation & Work Style', text: 'I procrastinate often.' },
{ category: 'Motivation & Work Style', text: 'I prefer having a structured plan.' },
{ category: 'Motivation & Work Style', text: 'I finish what I start.' },
{ category: 'Motivation & Work Style', text: 'I lose interest quickly in tasks.' },
{ category: 'Social & Relationships', text: 'I feel energized being around people.' },
{ category: 'Social & Relationships', text: 'I prefer spending time alone.' },
{ category: 'Social & Relationships', text: 'I avoid conflict when possible.' },
{ category: 'Social & Relationships', text: 'I am comfortable being direct with others.' },
{ category: 'Social & Relationships', text: 'I find it easy to connect with people.' },
{ category: 'Social & Relationships', text: 'I value deep relationships over many connections.' },
{ category: 'Decision-Making & Thinking Style', text: 'I rely more on logic than emotion.' },
{ category: 'Decision-Making & Thinking Style', text: 'I trust my gut when making decisions.' },
{ category: 'Decision-Making & Thinking Style', text: 'I tend to overthink decisions.' },
{ category: 'Decision-Making & Thinking Style', text: 'I act quickly without overanalyzing.' },
{ category: 'Decision-Making & Thinking Style', text: 'I am comfortable with uncertainty.' },
{ category: 'Decision-Making & Thinking Style', text: 'I prefer clear answers over open-ended possibilities.' },
{ category: 'Challenges & Struggles', text: 'I feel stuck in my current situation.' },
{ category: 'Challenges & Struggles', text: 'I avoid things I know I should do.' },
{ category: 'Challenges & Struggles', text: 'I struggle with self-doubt.' },
{ category: 'Challenges & Struggles', text: 'I feel in control of my life.' },
{ category: 'Challenges & Struggles', text: 'I get easily discouraged by setbacks.' },
{ category: 'Challenges & Struggles', text: 'I push through challenges even when it is hard.' },
{ category: 'Preferred Guidance Style', text: 'I prefer direct and blunt advice.' },
{ category: 'Preferred Guidance Style', text: 'I prefer gentle and supportive advice.' },
{ category: 'Preferred Guidance Style', text: 'I want someone to challenge me.' },
{ category: 'Preferred Guidance Style', text: 'I want emotional support more than solutions.' },
{ category: 'Preferred Guidance Style', text: 'I like being held accountable.' },
{ category: 'Preferred Guidance Style', text: 'I prefer figuring things out on my own.' },
{ category: 'Preferred Guidance Style', text: 'I prefer step-by-step guidance.' },
{ category: 'Preferred Guidance Style', text: 'I prefer big-picture advice.' },
{ category: 'Future & Aspirations', text: 'I have clear goals I am working toward.' },
{ category: 'Future & Aspirations', text: 'I feel excited about my future.' },
{ category: 'Future & Aspirations', text: 'I feel anxious about my future.' },
{ category: 'Future & Aspirations', text: 'I know what success looks like for me.' },
{ category: 'Future & Aspirations', text: 'I feel like I am making progress.' },
];
function missingApiKeyError() {
const error = new Error(
'OPENAI_API_KEY is missing. Add it to a local .env file before starting the server.'
);
error.code = MISSING_KEY_CODE;
return error;
}
function extractReplyText(data) {
if (typeof data?.output_text === 'string' && data.output_text.trim()) {
return data.output_text.trim();
}
const outputItems = Array.isArray(data?.output) ? data.output : [];
const messageTexts = outputItems
.flatMap((item) => (Array.isArray(item?.content) ? item.content : []))
.filter((item) => item?.type === 'output_text' && typeof item.text === 'string')
.map((item) => item.text.trim())
.filter(Boolean);
return messageTexts.join('\n').trim();
}
function buildBernardInstructions(context) {
const base = `You are Bernard — the user's older brother, about 3 to 5 years older than them. You grew up together. You know them. You care about them more than almost anyone else does.
You are not a therapist, not a life coach, not a chatbot. You are their big brother. That means:
- You speak like a real person: warm, a little casual, never robotic.
- You are honest but never harsh. If something needs to be said, you say it gently.
- You are genuinely encouraging — you believe in this person even when they do not believe in themselves.
- You have been through hard things too. You do not pretend life is easy. But you do know it gets better.
- You actually listen. You respond to what they said, not a generic version of it.
- You do not lecture. You do not give bullet-point life plans unless they ask for one.
- When someone is hurting — anxious, doubting themselves, scared, grieving, or just feeling lost — you do not minimize it. You sit with them for a moment. You acknowledge it. Then you help them see they can get through it.
- You are the person they can come to when they do not feel like they can talk to anyone else.
Tone: conversational, warm, grounded. Short to medium length replies. Like a real text conversation with someone who genuinely cares. Avoid clinical language, hollow affirmations, or anything that sounds like a helpline script.
If someone brings up serious self-harm or crisis, gently and warmly encourage them to speak to someone who can properly support them — but do so as a caring older sibling would, not as a liability disclaimer.`;
if (!context || !context.hasQuestionnaireData) {
return base;
}
const topFiveLines = (context.topFiveEmotions || [])
.map((e, i) => ` ${i + 1}. ${e.name} — ${e.percentage}% of their emotional profile`)
.join('\n');
const analyticsBlock = `
---
Here is what you know about this person from their personality questionnaire. Use this to inform your tone and what you pick up on — but do not read it out to them directly or reference the percentages explicitly. Let it shape how you understand them.
Personality Type: ${context.personalityType}
Composite Score: ${context.compositeScore} / 10
Top emotional patterns right now (highest to lowest):
${topFiveLines}
---
Some things this tells you:
- If their top emotions include sadness, burnout, or selfDoubt — they may be carrying more than they show. Be especially gentle and present.
- If they score high on futureAnxiety or overthinking — they likely need reassurance and grounding more than advice.
- If motivation and ambition are high — they are driven but may be pushing themselves too hard. Remind them rest is not failure.
- If loyalty is high — relationships and trust matter deeply to them. Honour that.
- If aggression or guilt are prominent — there may be tension or shame underneath. Be patient and non-judgmental.
- If focus and ambition dominate — they are goal-oriented. Help them stay balanced without burning out.
You do not need to bring up these traits unless they come up naturally in conversation. They are context, not a script.`;
return base + analyticsBlock;
}
async function getBernardReply(message, context = null) {
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
throw missingApiKeyError();
}
try {
const response = await fetch(OPENAI_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: OPENAI_MODEL,
instructions: buildBernardInstructions(context),
input: message,
}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`OpenAI API request failed (${response.status}): ${errorText}`);
}
const data = await response.json();
const reply = extractReplyText(data);
return reply || BERNARD_FALLBACK_REPLY;
} catch (error) {
if (error.code === MISSING_KEY_CODE) {
throw error;
}
console.error('OpenAI chat request failed:', error);
return BERNARD_FALLBACK_REPLY;
}
}
async function getBernardTraitScores(answers) {
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) throw missingApiKeyError();
const questionLines = QUESTION_TEXTS.map((q, i) => {
const ans = answers[i];
const label = ANSWER_LABELS[ans] || 'Not answered';
const score = Number.isInteger(ans) ? `${ans}/5` : 'N/A';
return `Q${i + 1} [${q.category}]: "${q.text}" → ${label} (${score})`;
}).join('\n');
const prompt = `You are analyzing a user's personality questionnaire. Based on their responses, score each of the 12 personality traits from 0 to 10.
IMPORTANT CONSTRAINT: No 6 or more traits may share the same score value. Scores must reflect genuine differentiation based on the answers.
Questionnaire responses (scale: 1=Disagree, 2=Slightly disagree, 3=Maybe, 4=Slightly agree, 5=Agree):
${questionLines}
Traits to score (0–10):
- happy: overall happiness and positive affect
- sadness: level of sadness or low mood
- motivation: drive and energy to pursue goals
- futureAnxiety: anxiety or worry about the future
- overthinking: tendency to ruminate or overanalyze
- ambition: ambition and goal orientation
- aggression: assertiveness or aggressive tendencies
- loyalty: commitment to relationships and values
- guilt: feelings of guilt or self-blame
- burnout: emotional exhaustion or burnout
- selfDoubt: self-doubt and lack of confidence
- focus: ability to stay focused and disciplined
Return ONLY valid JSON with no extra text, markdown, or explanation:
{"happy":0,"sadness":0,"motivation":0,"futureAnxiety":0,"overthinking":0,"ambition":0,"aggression":0,"loyalty":0,"guilt":0,"burnout":0,"selfDoubt":0,"focus":0}`;
const response = await fetch(OPENAI_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: OPENAI_MODEL,
instructions: 'You are a personality analysis system. Return only valid JSON with no markdown, no explanation, just the raw JSON object.',
input: prompt,
}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`OpenAI API request failed (${response.status}): ${errorText}`);
}
const data = await response.json();
const text = extractReplyText(data);
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (!jsonMatch) throw new Error('Invalid trait scores response from AI');
const parsed = JSON.parse(jsonMatch[0]);
const validated = {};
for (const key of TRAIT_KEYS) {
const val = Number(parsed[key]);
validated[key] = Number.isFinite(val) ? Math.max(0, Math.min(10, Math.round(val))) : 5;
}
return validated;
}
module.exports = {
getBernardReply,
getBernardTraitScores,
MISSING_KEY_CODE,
};