File size: 12,011 Bytes
2639a25
 
 
 
 
 
 
9f1c9fa
2639a25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ffa0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2639a25
 
9f1c9fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ffa0fa
 
 
 
 
 
 
9f1c9fa
3ffa0fa
9f1c9fa
 
 
 
 
 
 
 
 
 
 
3ffa0fa
 
 
 
 
9f1c9fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ffa0fa
 
 
9f1c9fa
 
 
 
 
 
 
 
 
3ffa0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f1c9fa
 
 
 
 
 
 
 
 
 
 
 
 
 
3ffa0fa
9f1c9fa
 
 
 
3ffa0fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f1c9fa
3ffa0fa
9f1c9fa
 
 
 
 
 
3ffa0fa
 
 
 
 
 
 
 
 
 
 
9f1c9fa
 
 
 
 
 
 
 
 
 
 
 
2639a25
 
 
 
 
 
 
9f1c9fa
 
 
 
 
3ffa0fa
 
 
 
 
2639a25
 
 
 
 
 
 
 
 
 
 
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
"""
PsycheOS — HuggingFace Spaces API Entrypoint
Exposes a FastAPI app so Spaces can run this as a server.
"""

from pydantic import BaseModel
from fastapi import FastAPI
from fastapi.responses import HTMLResponse

from agents.graph import run_psycheos

app = FastAPI(title="PsycheOS API", version="2.0.0")


class ChatRequest(BaseModel):
    message: str
    memory_hint: str = ""
    session: int = 1
    mode_hint: str = ""
    trust_level: float = 0.5
    session_history: list = []


def _baseline_chat(message: str) -> dict:
    """
    Simple pre-training baseline heuristic for demo comparison.
    This is intentionally weaker than the trained multi-agent pipeline.
    """
    text = message.lower()

    severe_hits = [
        "suicide", "kill myself", "end my life", "goodbye", "can't do this", "plan",
        "pills", "hurt myself", "self harm", "not alive",
    ]
    moderate_hits = [
        "anxious", "panic", "can't sleep", "depressed", "hopeless", "empty",
        "cry", "overwhelmed", "lost",
    ]
    mild_hits = ["stressed", "tired", "down", "sad", "low", "worried"]

    def count_hits(words):
        return sum(1 for w in words if w in text)

    severe = count_hits(severe_hits)
    moderate = count_hits(moderate_hits)
    mild = count_hits(mild_hits)

    if severe > 0:
        distress = 5
    elif moderate >= 2:
        distress = 4
    elif moderate == 1:
        distress = 3
    elif mild >= 2:
        distress = 2
    else:
        distress = 1

    escalate = distress >= 4
    response = (
        "I hear you, and I am glad you shared this. "
        "Can you tell me a bit more about what feels hardest right now?"
    )
    if escalate:
        response = (
            "Thank you for telling me this. Your safety matters right now. "
            "Please reach out to local emergency services or a trusted person immediately."
        )

    return {
        "source": "baseline",
        "distress_level": distress,
        "response": response,
        "escalate": escalate,
        "detected_mode": "open",
        "reward": 0.0,
        "dpo_score": 0.0,
        "f1_score": 0.0,
    }


@app.get("/")
def root():
    return HTMLResponse(
        """
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>PsycheOS</title>
  <style>
    :root{
      --bg:#0b1020; --card:#121a30; --line:#243253; --txt:#e8eeff; --muted:#9db0e6;
      --accent:#7c8bff; --accent2:#f672a7; --ok:#35d39a; --warn:#f4c95d; --danger:#ff7a7a;
    }
    *{box-sizing:border-box}
    body{
      margin:0; font-family:Inter,system-ui,-apple-system,Segoe UI,Roboto,Arial,sans-serif;
      background:radial-gradient(1200px 600px at 10% -10%, #243253 0%, transparent 60%), var(--bg);
      color:var(--txt);
    }
    .wrap{max-width:980px;margin:28px auto;padding:0 16px;}
    .hero{
      border:1px solid var(--line); background:linear-gradient(140deg,#111a31,#0d1428);
      border-radius:16px; padding:20px;
    }
    .title{margin:0;font-size:30px;font-weight:800;letter-spacing:.2px}
    .sub{margin:6px 0 0;color:var(--muted);font-size:14px}
    .grid{display:grid;grid-template-columns:1fr 310px;gap:16px;margin-top:16px}
    .panel{border:1px solid var(--line);background:var(--card);border-radius:14px;padding:14px}
    .chatlog{height:420px;overflow:auto;padding:8px;border:1px solid var(--line);border-radius:12px;background:#0e1630}
    .msg{max-width:82%;padding:10px 12px;border-radius:12px;margin:8px 0;line-height:1.45;font-size:14px;white-space:pre-wrap}
    .u{margin-left:auto;background:#1b2b54;border:1px solid #2e4580}
    .a{margin-right:auto;background:#1b1730;border:1px solid #3b2c63}
    .meta{font-size:12px;color:var(--muted);margin-top:6px}
    .row{display:flex;gap:8px;margin-top:10px}
    textarea{
      flex:1;height:78px;resize:vertical;border-radius:10px;border:1px solid var(--line);
      background:#0c1430;color:var(--txt);padding:10px;font:inherit
    }
    button{
      border:0;border-radius:10px;padding:0 14px;font-weight:700;color:white;cursor:pointer;
      background:linear-gradient(135deg,var(--accent),var(--accent2))
    }
    .k{display:flex;justify-content:space-between;margin:10px 0;padding:8px 0;border-bottom:1px dashed #2a385f;font-size:13px}
    .badge{display:inline-block;padding:4px 8px;border-radius:999px;border:1px solid #334a7d;color:#cfe0ff;background:#132043;font-size:12px}
    .switch{display:flex;gap:6px;align-items:center;flex-wrap:wrap;margin-top:10px}
    .chip{border:1px solid #334a7d;background:#0f1e40;color:#b8cbff;padding:6px 10px;border-radius:999px;font-size:12px;cursor:pointer}
    .chip.active{background:linear-gradient(135deg,var(--accent),var(--accent2));color:#fff;border-color:transparent}
    .compare{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:8px}
    .cmpbox{border:1px solid var(--line);border-radius:10px;padding:8px;background:#0d1630}
    .cmptitle{font-size:12px;color:#b5c8ff;margin-bottom:6px}
    .cmptext{font-size:13px;line-height:1.45;white-space:pre-wrap}
    .ok{color:var(--ok)} .warn{color:var(--warn)} .danger{color:var(--danger)}
    @media (max-width:880px){.grid{grid-template-columns:1fr}.compare{grid-template-columns:1fr}}
  </style>
</head>
<body>
  <div class="wrap">
    <section class="hero">
      <h1 class="title">PsycheOS</h1>
      <p class="sub">Multi-agent mental-health RL environment demo • FastAPI + Docker Space</p>
    </section>

    <div class="grid">
      <section class="panel">
        <div class="switch">
          <span class="badge">Demo Mode</span>
          <button id="mode-trained" class="chip active" type="button">Trained only</button>
          <button id="mode-compare" class="chip" type="button">Before vs Trained</button>
        </div>
        <div id="chatlog" class="chatlog">
          <div class="msg a">Hi, I am PsycheOS. Tell me what is on your mind.</div>
        </div>
        <div class="row">
          <textarea id="input" placeholder="Share what's on your mind..."></textarea>
          <button id="send">Send</button>
        </div>
      </section>

      <aside class="panel">
        <div class="badge">Live Agent Signals</div>
        <div class="k"><span>Distress level</span><strong id="distress">-</strong></div>
        <div class="k"><span>Escalation</span><strong id="escalate">-</strong></div>
        <div class="k"><span>Detected mode</span><strong id="mode">-</strong></div>
        <div class="k"><span>Reward</span><strong id="reward">-</strong></div>
        <div class="k"><span>DPO score</span><strong id="dpo">-</strong></div>
        <div class="k"><span>F1 score</span><strong id="f1">-</strong></div>
        <div class="meta">Tip: judges can also call <code>/chat</code> directly for API-level evaluation.</div>
      </aside>
    </div>
  </div>

  <script>
    const chatlog = document.getElementById("chatlog");
    const input = document.getElementById("input");
    const send = document.getElementById("send");
    const modeTrainedBtn = document.getElementById("mode-trained");
    const modeCompareBtn = document.getElementById("mode-compare");
    let compareMode = false;

    function addMsg(text, cls){
      const d = document.createElement("div");
      d.className = "msg " + cls;
      d.textContent = text;
      chatlog.appendChild(d);
      chatlog.scrollTop = chatlog.scrollHeight;
    }

    function addCompare(before, trained){
      const wrap = document.createElement("div");
      wrap.className = "msg a";
      wrap.innerHTML = `
        <div class="compare">
          <div class="cmpbox">
            <div class="cmptitle">Before (baseline)</div>
            <div class="cmptext">${before}</div>
          </div>
          <div class="cmpbox">
            <div class="cmptitle">Trained (PsycheOS)</div>
            <div class="cmptext">${trained}</div>
          </div>
        </div>
      `;
      chatlog.appendChild(wrap);
      chatlog.scrollTop = chatlog.scrollHeight;
    }

    function setSignal(id, value, level){
      const el = document.getElementById(id);
      el.textContent = value;
      el.className = level || "";
    }

    async function runChat(){
      const message = input.value.trim();
      if(!message) return;
      addMsg(message, "u");
      input.value = "";
      send.disabled = true;
      send.textContent = "Sending...";
      try{
        const trainedReq = fetch("/chat", {
          method: "POST",
          headers: {"Content-Type":"application/json"},
          body: JSON.stringify({message, session: 1, trust_level: 0.5, session_history: []})
        });

        if (compareMode){
          const baselineReq = fetch("/chat_baseline", {
            method: "POST",
            headers: {"Content-Type":"application/json"},
            body: JSON.stringify({message, session: 1, trust_level: 0.5, session_history: []})
          });

          const [trainedRes, baselineRes] = await Promise.all([trainedReq, baselineReq]);
          if(!trainedRes.ok || !baselineRes.ok) throw new Error("Compare request failed");

          const trained = await trainedRes.json();
          const baseline = await baselineRes.json();
          addCompare(
            baseline.response || "(no response)",
            trained.response || "(no response)"
          );

          setSignal("distress", `${baseline.distress_level} → ${trained.distress_level}`, (trained.distress_level >= 4 ? "danger" : trained.distress_level >= 3 ? "warn" : "ok"));
          setSignal("escalate", `${baseline.escalate ? "YES" : "NO"} → ${trained.escalate ? "YES" : "NO"}`, trained.escalate ? "danger" : "ok");
          setSignal("mode", trained.detected_mode || "-");
          setSignal("reward", trained.reward ?? "-");
          setSignal("dpo", trained.dpo_score ?? "-");
          setSignal("f1", trained.f1_score ?? "-");
        } else {
          const trainedRes = await trainedReq;
          if(!trainedRes.ok) throw new Error("Request failed");
          const data = await trainedRes.json();
          addMsg(data.response || "(no response)", "a");
          setSignal("distress", data.distress_level ?? "-", (data.distress_level >= 4 ? "danger" : data.distress_level >= 3 ? "warn" : "ok"));
          setSignal("escalate", data.escalate ? "YES" : "NO", data.escalate ? "danger" : "ok");
          setSignal("mode", data.detected_mode || "-");
          setSignal("reward", data.reward ?? "-");
          setSignal("dpo", data.dpo_score ?? "-");
          setSignal("f1", data.f1_score ?? "-");
        }
      } catch(e){
        addMsg("Error: could not reach chat endpoints.", "a");
      } finally {
        send.disabled = false;
        send.textContent = "Send";
      }
    }

    modeTrainedBtn.addEventListener("click", () => {
      compareMode = false;
      modeTrainedBtn.classList.add("active");
      modeCompareBtn.classList.remove("active");
    });
    modeCompareBtn.addEventListener("click", () => {
      compareMode = true;
      modeCompareBtn.classList.add("active");
      modeTrainedBtn.classList.remove("active");
    });

    send.addEventListener("click", runChat);
    input.addEventListener("keydown", (e) => {
      if (e.key === "Enter" && !e.shiftKey) {
        e.preventDefault();
        runChat();
      }
    });
  </script>
</body>
</html>
        """
    )


@app.get("/health")
def health():
    return {"healthy": True}


@app.get("/api/status")
def api_status():
    return {"status": "ok", "service": "PsycheOS API"}


@app.post("/chat_baseline")
def chat_baseline(payload: ChatRequest):
    return _baseline_chat(payload.message)


@app.post("/chat")
def chat(payload: ChatRequest):
    result = run_psycheos(
        message=payload.message,
        memory_hint=payload.memory_hint,
        session=payload.session,
        mode_hint=payload.mode_hint,
        trust_level=payload.trust_level,
        session_history=payload.session_history,
    )
    return result