Freakdivi commited on
Commit
9de202e
·
1 Parent(s): 2bd71de

updating app.py

Browse files
Files changed (1) hide show
  1. server/app.py +852 -8
server/app.py CHANGED
@@ -1,8 +1,9 @@
1
- """FastAPI server exposing HelpdeskEnv over HTTP."""
2
 
3
  from typing import Any, Dict, Optional
4
 
5
  from fastapi import FastAPI
 
6
  from pydantic import BaseModel
7
 
8
  from ..environment import HelpdeskEnv
@@ -11,6 +12,853 @@ from ..models import Action, Reward
11
  app = FastAPI(title="Helpdesk OpenEnv")
12
  _env: Optional[HelpdeskEnv] = None
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
  def get_env() -> HelpdeskEnv:
16
  global _env
@@ -41,13 +889,9 @@ def health() -> Dict[str, str]:
41
  return {"status": "healthy"}
42
 
43
 
44
- @app.get("/")
45
- def root() -> Dict[str, Any]:
46
- return {
47
- "name": "UPI Banking Support Environment",
48
- "status": "running",
49
- "endpoints": ["/health", "/reset", "/step", "/state"],
50
- }
51
 
52
 
53
  @app.post("/reset")
 
1
+ """FastAPI server exposing HelpdeskEnv over HTTP and a lightweight dashboard UI."""
2
 
3
  from typing import Any, Dict, Optional
4
 
5
  from fastapi import FastAPI
6
+ from fastapi.responses import HTMLResponse
7
  from pydantic import BaseModel
8
 
9
  from ..environment import HelpdeskEnv
 
12
  app = FastAPI(title="Helpdesk OpenEnv")
13
  _env: Optional[HelpdeskEnv] = None
14
 
15
+ UI_HTML = """<!DOCTYPE html>
16
+ <html lang="en">
17
+ <head>
18
+ <meta charset="utf-8" />
19
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
20
+ <title>UPI Banking Support Environment</title>
21
+ <style>
22
+ :root {
23
+ --bg: #f6f1e8;
24
+ --panel: rgba(255, 251, 245, 0.92);
25
+ --panel-strong: #fff9f0;
26
+ --ink: #1f1c17;
27
+ --muted: #6e6459;
28
+ --line: rgba(62, 47, 33, 0.14);
29
+ --accent: #156f63;
30
+ --accent-2: #d66b2d;
31
+ --accent-3: #2f5d9a;
32
+ --success: #2f8f57;
33
+ --danger: #b94133;
34
+ --shadow: 0 22px 60px rgba(75, 52, 27, 0.12);
35
+ --radius: 24px;
36
+ --radius-sm: 16px;
37
+ }
38
+
39
+ * {
40
+ box-sizing: border-box;
41
+ }
42
+
43
+ body {
44
+ margin: 0;
45
+ font-family: "Avenir Next", "Segoe UI", sans-serif;
46
+ color: var(--ink);
47
+ background:
48
+ radial-gradient(circle at top left, rgba(214, 107, 45, 0.18), transparent 32%),
49
+ radial-gradient(circle at top right, rgba(21, 111, 99, 0.18), transparent 28%),
50
+ linear-gradient(180deg, #f8f3eb 0%, #efe7d7 100%);
51
+ min-height: 100vh;
52
+ }
53
+
54
+ .shell {
55
+ width: min(1240px, calc(100vw - 32px));
56
+ margin: 24px auto 40px;
57
+ }
58
+
59
+ .hero {
60
+ background: linear-gradient(135deg, rgba(27, 75, 68, 0.96), rgba(17, 38, 59, 0.96));
61
+ color: #fdfaf3;
62
+ border-radius: 32px;
63
+ padding: 28px;
64
+ box-shadow: var(--shadow);
65
+ position: relative;
66
+ overflow: hidden;
67
+ }
68
+
69
+ .hero::after {
70
+ content: "";
71
+ position: absolute;
72
+ inset: auto -60px -80px auto;
73
+ width: 240px;
74
+ height: 240px;
75
+ border-radius: 50%;
76
+ background: rgba(255, 214, 102, 0.18);
77
+ filter: blur(4px);
78
+ }
79
+
80
+ .hero-top {
81
+ display: flex;
82
+ justify-content: space-between;
83
+ gap: 16px;
84
+ align-items: start;
85
+ }
86
+
87
+ h1, h2, h3, p {
88
+ margin: 0;
89
+ }
90
+
91
+ .eyebrow {
92
+ font-size: 12px;
93
+ text-transform: uppercase;
94
+ letter-spacing: 0.22em;
95
+ color: rgba(253, 250, 243, 0.72);
96
+ margin-bottom: 10px;
97
+ }
98
+
99
+ .hero h1 {
100
+ font-size: clamp(34px, 5vw, 58px);
101
+ line-height: 0.96;
102
+ max-width: 760px;
103
+ }
104
+
105
+ .hero p {
106
+ margin-top: 16px;
107
+ max-width: 720px;
108
+ color: rgba(253, 250, 243, 0.78);
109
+ font-size: 18px;
110
+ line-height: 1.5;
111
+ }
112
+
113
+ .hero-links {
114
+ display: flex;
115
+ gap: 10px;
116
+ flex-wrap: wrap;
117
+ margin-top: 22px;
118
+ }
119
+
120
+ .pill {
121
+ display: inline-flex;
122
+ align-items: center;
123
+ gap: 8px;
124
+ padding: 10px 14px;
125
+ border-radius: 999px;
126
+ background: rgba(255, 255, 255, 0.12);
127
+ color: #fff;
128
+ text-decoration: none;
129
+ border: 1px solid rgba(255, 255, 255, 0.16);
130
+ backdrop-filter: blur(10px);
131
+ }
132
+
133
+ .status-chip {
134
+ min-width: 170px;
135
+ padding: 14px 16px;
136
+ border-radius: 20px;
137
+ background: rgba(255, 251, 240, 0.12);
138
+ border: 1px solid rgba(255, 251, 240, 0.18);
139
+ text-align: right;
140
+ }
141
+
142
+ .status-chip strong {
143
+ display: block;
144
+ font-size: 11px;
145
+ letter-spacing: 0.18em;
146
+ text-transform: uppercase;
147
+ color: rgba(253, 250, 243, 0.7);
148
+ margin-bottom: 8px;
149
+ }
150
+
151
+ .status-chip span {
152
+ font-size: 24px;
153
+ font-weight: 700;
154
+ }
155
+
156
+ .grid {
157
+ display: grid;
158
+ grid-template-columns: 1.45fr 1fr;
159
+ gap: 20px;
160
+ margin-top: 20px;
161
+ }
162
+
163
+ .card {
164
+ background: var(--panel);
165
+ border: 1px solid var(--line);
166
+ border-radius: var(--radius);
167
+ box-shadow: var(--shadow);
168
+ backdrop-filter: blur(16px);
169
+ padding: 22px;
170
+ }
171
+
172
+ .section-title {
173
+ font-size: 14px;
174
+ text-transform: uppercase;
175
+ letter-spacing: 0.18em;
176
+ color: var(--muted);
177
+ margin-bottom: 16px;
178
+ }
179
+
180
+ .metrics {
181
+ display: grid;
182
+ grid-template-columns: repeat(4, minmax(0, 1fr));
183
+ gap: 14px;
184
+ margin-top: 20px;
185
+ }
186
+
187
+ .metric {
188
+ border-radius: 22px;
189
+ padding: 18px;
190
+ color: white;
191
+ min-height: 128px;
192
+ display: flex;
193
+ flex-direction: column;
194
+ justify-content: space-between;
195
+ }
196
+
197
+ .metric strong {
198
+ font-size: 12px;
199
+ letter-spacing: 0.18em;
200
+ text-transform: uppercase;
201
+ opacity: 0.9;
202
+ }
203
+
204
+ .metric span {
205
+ font-size: 36px;
206
+ font-weight: 700;
207
+ line-height: 1;
208
+ }
209
+
210
+ .metric small {
211
+ font-size: 14px;
212
+ opacity: 0.9;
213
+ }
214
+
215
+ .metric.reward { background: linear-gradient(135deg, #156f63, #2f8f57); }
216
+ .metric.task { background: linear-gradient(135deg, #ca5e2c, #df8b2a); }
217
+ .metric.turn { background: linear-gradient(135deg, #3158a6, #4b7ae0); }
218
+ .metric.done { background: linear-gradient(135deg, #56406f, #79559e); }
219
+
220
+ .message-box,
221
+ .stream-box,
222
+ .info-box,
223
+ .json-box {
224
+ background: rgba(255, 255, 255, 0.58);
225
+ border: 1px solid rgba(89, 67, 43, 0.12);
226
+ border-radius: 20px;
227
+ padding: 18px;
228
+ }
229
+
230
+ .message-box {
231
+ min-height: 160px;
232
+ }
233
+
234
+ .message-label {
235
+ font-size: 12px;
236
+ text-transform: uppercase;
237
+ letter-spacing: 0.16em;
238
+ color: var(--muted);
239
+ margin-bottom: 12px;
240
+ }
241
+
242
+ .message-text {
243
+ font-size: 22px;
244
+ line-height: 1.45;
245
+ }
246
+
247
+ .hint {
248
+ margin-top: 16px;
249
+ padding: 14px 16px;
250
+ border-radius: 16px;
251
+ background: rgba(21, 111, 99, 0.1);
252
+ border: 1px solid rgba(21, 111, 99, 0.22);
253
+ color: #185046;
254
+ line-height: 1.5;
255
+ }
256
+
257
+ .timeline {
258
+ display: flex;
259
+ flex-direction: column;
260
+ gap: 12px;
261
+ max-height: 360px;
262
+ overflow: auto;
263
+ padding-right: 4px;
264
+ }
265
+
266
+ .bubble {
267
+ border-radius: 18px;
268
+ padding: 14px 16px;
269
+ border: 1px solid rgba(79, 58, 34, 0.1);
270
+ background: rgba(255, 255, 255, 0.72);
271
+ }
272
+
273
+ .bubble.agent {
274
+ background: rgba(214, 107, 45, 0.11);
275
+ border-color: rgba(214, 107, 45, 0.22);
276
+ }
277
+
278
+ .bubble.user {
279
+ background: rgba(21, 111, 99, 0.09);
280
+ border-color: rgba(21, 111, 99, 0.18);
281
+ }
282
+
283
+ .bubble strong {
284
+ display: block;
285
+ font-size: 11px;
286
+ letter-spacing: 0.16em;
287
+ text-transform: uppercase;
288
+ color: var(--muted);
289
+ margin-bottom: 8px;
290
+ }
291
+
292
+ .form-grid {
293
+ display: grid;
294
+ grid-template-columns: repeat(2, minmax(0, 1fr));
295
+ gap: 14px;
296
+ }
297
+
298
+ label {
299
+ display: block;
300
+ font-size: 13px;
301
+ letter-spacing: 0.06em;
302
+ text-transform: uppercase;
303
+ color: var(--muted);
304
+ margin-bottom: 8px;
305
+ }
306
+
307
+ input, select, textarea {
308
+ width: 100%;
309
+ border: 1px solid rgba(75, 55, 33, 0.16);
310
+ background: rgba(255, 255, 255, 0.92);
311
+ color: var(--ink);
312
+ border-radius: 16px;
313
+ padding: 14px 15px;
314
+ font: inherit;
315
+ }
316
+
317
+ textarea {
318
+ min-height: 120px;
319
+ resize: vertical;
320
+ }
321
+
322
+ .full {
323
+ grid-column: 1 / -1;
324
+ }
325
+
326
+ .button-row {
327
+ display: flex;
328
+ flex-wrap: wrap;
329
+ gap: 12px;
330
+ margin-top: 18px;
331
+ }
332
+
333
+ button {
334
+ border: 0;
335
+ border-radius: 999px;
336
+ padding: 14px 18px;
337
+ font: inherit;
338
+ font-weight: 700;
339
+ cursor: pointer;
340
+ transition: transform 0.15s ease, opacity 0.15s ease;
341
+ }
342
+
343
+ button:hover {
344
+ transform: translateY(-1px);
345
+ }
346
+
347
+ button.primary {
348
+ background: linear-gradient(135deg, #156f63, #2f8f57);
349
+ color: white;
350
+ }
351
+
352
+ button.secondary {
353
+ background: rgba(49, 93, 154, 0.12);
354
+ color: #24497d;
355
+ }
356
+
357
+ button.ghost {
358
+ background: rgba(31, 28, 23, 0.07);
359
+ color: var(--ink);
360
+ }
361
+
362
+ button:disabled {
363
+ opacity: 0.5;
364
+ cursor: not-allowed;
365
+ transform: none;
366
+ }
367
+
368
+ .mini-grid {
369
+ display: grid;
370
+ grid-template-columns: repeat(2, minmax(0, 1fr));
371
+ gap: 14px;
372
+ margin-top: 18px;
373
+ }
374
+
375
+ .kv {
376
+ border-radius: 18px;
377
+ padding: 16px;
378
+ background: rgba(255, 255, 255, 0.58);
379
+ border: 1px solid rgba(89, 67, 43, 0.12);
380
+ min-height: 112px;
381
+ }
382
+
383
+ .kv strong {
384
+ display: block;
385
+ font-size: 11px;
386
+ letter-spacing: 0.16em;
387
+ text-transform: uppercase;
388
+ color: var(--muted);
389
+ margin-bottom: 10px;
390
+ }
391
+
392
+ .mono {
393
+ font-family: "SFMono-Regular", "Menlo", monospace;
394
+ font-size: 14px;
395
+ line-height: 1.55;
396
+ white-space: pre-wrap;
397
+ word-break: break-word;
398
+ }
399
+
400
+ .tags {
401
+ display: flex;
402
+ flex-wrap: wrap;
403
+ gap: 8px;
404
+ }
405
+
406
+ .tag {
407
+ padding: 8px 12px;
408
+ border-radius: 999px;
409
+ background: rgba(49, 93, 154, 0.1);
410
+ color: #27497a;
411
+ font-size: 13px;
412
+ border: 1px solid rgba(49, 93, 154, 0.14);
413
+ }
414
+
415
+ .muted {
416
+ color: var(--muted);
417
+ }
418
+
419
+ .footer-note {
420
+ margin-top: 18px;
421
+ color: var(--muted);
422
+ font-size: 14px;
423
+ line-height: 1.5;
424
+ }
425
+
426
+ @media (max-width: 980px) {
427
+ .grid,
428
+ .metrics,
429
+ .form-grid,
430
+ .mini-grid {
431
+ grid-template-columns: 1fr;
432
+ }
433
+
434
+ .hero-top {
435
+ flex-direction: column;
436
+ }
437
+
438
+ .status-chip {
439
+ text-align: left;
440
+ }
441
+ }
442
+ </style>
443
+ </head>
444
+ <body>
445
+ <div class="shell">
446
+ <section class="hero">
447
+ <div class="hero-top">
448
+ <div>
449
+ <div class="eyebrow">HF Space Dashboard</div>
450
+ <h1>UPI Banking Support Environment</h1>
451
+ <p>Run the benchmark like an operator: reset an episode, choose the exact action your agent would take, and inspect the live observation, conversation, and current reward after each step.</p>
452
+ <div class="hero-links">
453
+ <a class="pill" href="/health" target="_blank" rel="noreferrer">Health</a>
454
+ <a class="pill" href="/docs" target="_blank" rel="noreferrer">API Docs</a>
455
+ <a class="pill" href="/state" target="_blank" rel="noreferrer">Raw State</a>
456
+ </div>
457
+ </div>
458
+ <div class="status-chip">
459
+ <strong>Environment</strong>
460
+ <span id="env-status">Checking...</span>
461
+ </div>
462
+ </div>
463
+ <div class="metrics">
464
+ <div class="metric reward">
465
+ <strong>Current Reward</strong>
466
+ <span id="metric-reward">0.000</span>
467
+ <small>Most recent reward value</small>
468
+ </div>
469
+ <div class="metric task">
470
+ <strong>Difficulty</strong>
471
+ <span id="metric-task">-</span>
472
+ <small>Current episode track</small>
473
+ </div>
474
+ <div class="metric turn">
475
+ <strong>Turn</strong>
476
+ <span id="metric-turn">0</span>
477
+ <small>Current step count</small>
478
+ </div>
479
+ <div class="metric done">
480
+ <strong>Status</strong>
481
+ <span id="metric-done">Idle</span>
482
+ <small>Episode completion</small>
483
+ </div>
484
+ </div>
485
+ </section>
486
+
487
+ <div class="grid">
488
+ <section class="card">
489
+ <div class="section-title">Current Ticket</div>
490
+ <div class="message-box">
491
+ <div class="message-label">Customer Message</div>
492
+ <div class="message-text" id="customer-message">Reset the environment to load a ticket.</div>
493
+ </div>
494
+ <div class="hint" id="hint-box">Pick a difficulty, reset the env, then use one of your supported actions. This UI is tuned for classify, FAQ lookup, clarification, reply, escalate, and resolve flows.</div>
495
+ <div class="mini-grid">
496
+ <div class="kv">
497
+ <strong>Case</strong>
498
+ <div class="mono" id="case-id">-</div>
499
+ </div>
500
+ <div class="kv">
501
+ <strong>Required Slots</strong>
502
+ <div id="required-slots" class="tags"><span class="muted">No episode loaded yet.</span></div>
503
+ </div>
504
+ <div class="kv">
505
+ <strong>Available Actions</strong>
506
+ <div id="available-actions" class="tags"><span class="muted">Reset to populate actions.</span></div>
507
+ </div>
508
+ <div class="kv">
509
+ <strong>Collected Facts</strong>
510
+ <div class="mono" id="collected-facts">-</div>
511
+ </div>
512
+ </div>
513
+ </section>
514
+
515
+ <section class="card">
516
+ <div class="section-title">Action Console</div>
517
+ <div class="form-grid">
518
+ <div>
519
+ <label for="difficulty">Difficulty</label>
520
+ <select id="difficulty">
521
+ <option value="easy">Easy</option>
522
+ <option value="medium">Medium</option>
523
+ <option value="hard">Hard</option>
524
+ </select>
525
+ </div>
526
+ <div>
527
+ <label for="action-type">Action Type</label>
528
+ <select id="action-type">
529
+ <option value="classify">classify</option>
530
+ <option value="lookup_faq">lookup_faq</option>
531
+ <option value="ask_clarification">ask_clarification</option>
532
+ <option value="reply">reply</option>
533
+ <option value="escalate">escalate</option>
534
+ <option value="resolve_ticket">resolve_ticket</option>
535
+ </select>
536
+ </div>
537
+ <div id="category-wrap">
538
+ <label for="category">Category</label>
539
+ <select id="category">
540
+ <option value="">Select category</option>
541
+ </select>
542
+ </div>
543
+ <div id="faq-wrap">
544
+ <label for="faq-id">FAQ</label>
545
+ <select id="faq-id">
546
+ <option value="">Select FAQ</option>
547
+ </select>
548
+ </div>
549
+ <div class="full" id="message-wrap">
550
+ <label for="message">Message</label>
551
+ <textarea id="message" placeholder="Write the agent message for clarification, reply, or escalation."></textarea>
552
+ </div>
553
+ </div>
554
+ <div class="button-row">
555
+ <button id="step-btn" class="primary">Execute Step</button>
556
+ <button id="reset-btn" class="secondary">Reset</button>
557
+ <button id="state-btn" class="ghost">Refresh State</button>
558
+ </div>
559
+ <div class="footer-note" id="action-help">Use `classify` for easy tasks, `lookup_faq` or `escalate` for medium tickets, and clarification plus reply plus resolve for hard tickets.</div>
560
+ </section>
561
+ </div>
562
+
563
+ <div class="grid">
564
+ <section class="card">
565
+ <div class="section-title">Conversation Timeline</div>
566
+ <div class="timeline" id="timeline">
567
+ <div class="bubble">
568
+ <strong>Waiting</strong>
569
+ Reset the environment to start an episode.
570
+ </div>
571
+ </div>
572
+ </section>
573
+
574
+ <section class="card">
575
+ <div class="section-title">Step Details</div>
576
+ <div class="mini-grid">
577
+ <div class="kv">
578
+ <strong>Current Reward Breakdown</strong>
579
+ <div class="mono" id="reward-breakdown">-</div>
580
+ </div>
581
+ <div class="kv">
582
+ <strong>Episode Info</strong>
583
+ <div class="mono" id="episode-info">-</div>
584
+ </div>
585
+ <div class="kv full">
586
+ <strong>Observation Snapshot</strong>
587
+ <div class="mono" id="observation-view">-</div>
588
+ </div>
589
+ </div>
590
+ </section>
591
+ </div>
592
+ </div>
593
+
594
+ <script>
595
+ const categoryChoices = [
596
+ "payment_failure",
597
+ "refund_delay",
598
+ "fraud_complaint",
599
+ "kyc_account_restriction",
600
+ "upi_pin_or_bank_linking"
601
+ ];
602
+
603
+ const faqChoices = [
604
+ ["faq_001", "Payment failed, money debited"],
605
+ ["faq_002", "Merchant unpaid after debit"],
606
+ ["faq_003", "Delayed refund"],
607
+ ["faq_004", "Merchant says refund complete"],
608
+ ["faq_005", "Unauthorized payment"],
609
+ ["faq_006", "KYC pending restriction"],
610
+ ["faq_007", "KYC submitted but blocked"],
611
+ ["faq_008", "UPI PIN setup/reset issue"],
612
+ ["faq_009", "Bank account linking issue"],
613
+ ["faq_010", "Scam collect request"]
614
+ ];
615
+
616
+ const state = {
617
+ observation: null,
618
+ reward: {
619
+ value: 0,
620
+ correctness: 0,
621
+ safety: 0,
622
+ resolution: 0,
623
+ efficiency: 0,
624
+ penalties: 0,
625
+ done: false
626
+ },
627
+ done: false,
628
+ info: {}
629
+ };
630
+
631
+ const els = {
632
+ envStatus: document.getElementById("env-status"),
633
+ metricReward: document.getElementById("metric-reward"),
634
+ metricTask: document.getElementById("metric-task"),
635
+ metricTurn: document.getElementById("metric-turn"),
636
+ metricDone: document.getElementById("metric-done"),
637
+ customerMessage: document.getElementById("customer-message"),
638
+ hintBox: document.getElementById("hint-box"),
639
+ caseId: document.getElementById("case-id"),
640
+ requiredSlots: document.getElementById("required-slots"),
641
+ availableActions: document.getElementById("available-actions"),
642
+ collectedFacts: document.getElementById("collected-facts"),
643
+ timeline: document.getElementById("timeline"),
644
+ rewardBreakdown: document.getElementById("reward-breakdown"),
645
+ episodeInfo: document.getElementById("episode-info"),
646
+ observationView: document.getElementById("observation-view"),
647
+ difficulty: document.getElementById("difficulty"),
648
+ actionType: document.getElementById("action-type"),
649
+ category: document.getElementById("category"),
650
+ faqId: document.getElementById("faq-id"),
651
+ message: document.getElementById("message"),
652
+ categoryWrap: document.getElementById("category-wrap"),
653
+ faqWrap: document.getElementById("faq-wrap"),
654
+ messageWrap: document.getElementById("message-wrap"),
655
+ actionHelp: document.getElementById("action-help"),
656
+ resetBtn: document.getElementById("reset-btn"),
657
+ stepBtn: document.getElementById("step-btn"),
658
+ stateBtn: document.getElementById("state-btn")
659
+ };
660
+
661
+ function populateSelect(select, values, formatter) {
662
+ const base = select.id === "faq-id"
663
+ ? '<option value="">Select FAQ</option>'
664
+ : '<option value="">Select category</option>';
665
+ select.innerHTML = base + values.map((value) => {
666
+ if (Array.isArray(value)) {
667
+ return `<option value="${value[0]}">${value[0]} · ${value[1]}</option>`;
668
+ }
669
+ const label = formatter ? formatter(value) : value;
670
+ return `<option value="${value}">${label}</option>`;
671
+ }).join("");
672
+ }
673
+
674
+ function renderTags(container, items) {
675
+ if (!items || items.length === 0) {
676
+ container.innerHTML = '<span class="muted">None</span>';
677
+ return;
678
+ }
679
+ container.innerHTML = items.map((item) => `<span class="tag">${item}</span>`).join("");
680
+ }
681
+
682
+ function safeJson(value) {
683
+ return JSON.stringify(value, null, 2);
684
+ }
685
+
686
+ function updateActionFields() {
687
+ const action = els.actionType.value;
688
+ const showCategory = action === "classify";
689
+ const showFaq = action === "lookup_faq";
690
+ const showMessage = ["ask_clarification", "reply", "escalate"].includes(action);
691
+
692
+ els.categoryWrap.style.display = showCategory ? "block" : "none";
693
+ els.faqWrap.style.display = showFaq ? "block" : "none";
694
+ els.messageWrap.style.display = showMessage ? "block" : "none";
695
+
696
+ const helpMap = {
697
+ classify: "Predict the banking issue category for the current ticket.",
698
+ lookup_faq: "Pick the FAQ entry your agent wants to use for guidance or routing.",
699
+ ask_clarification: "Ask the customer for more details before attempting a resolution.",
700
+ reply: "Send a safe support response to the user.",
701
+ escalate: "Escalate the ticket when the issue needs manual handling or fraud review.",
702
+ resolve_ticket: "Close the ticket when the case appears resolved."
703
+ };
704
+ els.actionHelp.textContent = helpMap[action] || "";
705
+ }
706
+
707
+ function updateView() {
708
+ const obs = state.observation;
709
+ const reward = state.reward || {};
710
+ const info = state.info || {};
711
+
712
+ els.metricReward.textContent = Number(reward.value || 0).toFixed(3);
713
+ els.metricTask.textContent = obs?.track || info.task_id || "-";
714
+ els.metricTurn.textContent = String(obs?.turn_number ?? info.turn_number ?? 0);
715
+ els.metricDone.textContent = state.done ? "Done" : (obs ? "Running" : "Idle");
716
+
717
+ els.customerMessage.textContent = obs?.customer_message || "Reset the environment to load a ticket.";
718
+ els.caseId.textContent = obs?.case_id || info.ticket_id || "-";
719
+ renderTags(els.requiredSlots, obs?.required_slots || []);
720
+ renderTags(els.availableActions, obs?.available_actions || []);
721
+
722
+ const collected = obs?.known_facts?.collected_slots || {};
723
+ els.collectedFacts.textContent = Object.keys(collected).length ? safeJson(collected) : "-";
724
+
725
+ const facts = obs?.known_facts || {};
726
+ const hintParts = [];
727
+ if (facts.clarification_received) hintParts.push("clarification received");
728
+ if (facts.faq_retrieved) hintParts.push("faq retrieved");
729
+ if (facts.issue_resolved) hintParts.push("issue resolved");
730
+ els.hintBox.textContent = hintParts.length
731
+ ? `Live env signals: ${hintParts.join(" · ")}.`
732
+ : "No progress flags are active yet. Choose the next action based on the ticket and available workflow.";
733
+
734
+ const history = obs?.conversation_history || [];
735
+ if (!history.length) {
736
+ els.timeline.innerHTML = '<div class="bubble"><strong>Waiting</strong>No actions yet. Reset the env, then execute a step.</div>';
737
+ } else {
738
+ els.timeline.innerHTML = history.map((entry, index) => {
739
+ const role = entry.role || "event";
740
+ return `<div class="bubble ${role}"><strong>${role} ${index + 1}</strong>${entry.content || "-"}</div>`;
741
+ }).join("");
742
+ }
743
+
744
+ els.rewardBreakdown.textContent = safeJson({
745
+ current_reward: Number(reward.value || 0).toFixed(3),
746
+ correctness: reward.correctness ?? 0,
747
+ safety: reward.safety ?? 0,
748
+ resolution: reward.resolution ?? 0,
749
+ efficiency: reward.efficiency ?? 0,
750
+ penalties: reward.penalties ?? 0
751
+ });
752
+ els.episodeInfo.textContent = safeJson({
753
+ done: state.done,
754
+ ...info
755
+ });
756
+ els.observationView.textContent = obs ? safeJson(obs) : "-";
757
+ }
758
+
759
+ async function handleResponse(response) {
760
+ if (!response.ok) {
761
+ const text = await response.text();
762
+ throw new Error(text || `Request failed with status ${response.status}`);
763
+ }
764
+ return response.json();
765
+ }
766
+
767
+ async function checkHealth() {
768
+ try {
769
+ const res = await fetch("/health");
770
+ const data = await handleResponse(res);
771
+ els.envStatus.textContent = data.status || "healthy";
772
+ } catch (error) {
773
+ els.envStatus.textContent = "unavailable";
774
+ }
775
+ }
776
+
777
+ async function resetEnv() {
778
+ els.resetBtn.disabled = true;
779
+ try {
780
+ const res = await fetch("/reset", {
781
+ method: "POST",
782
+ headers: { "Content-Type": "application/json" },
783
+ body: JSON.stringify({ task_id: els.difficulty.value })
784
+ });
785
+ const data = await handleResponse(res);
786
+ state.observation = data.observation;
787
+ state.reward = data.reward;
788
+ state.done = Boolean(data.done);
789
+ state.info = data.info || {};
790
+ updateView();
791
+ } finally {
792
+ els.resetBtn.disabled = false;
793
+ }
794
+ }
795
+
796
+ async function fetchState() {
797
+ els.stateBtn.disabled = true;
798
+ try {
799
+ const res = await fetch("/state");
800
+ const data = await handleResponse(res);
801
+ state.observation = data.observation;
802
+ updateView();
803
+ } catch (error) {
804
+ alert(`State unavailable: ${error.message}`);
805
+ } finally {
806
+ els.stateBtn.disabled = false;
807
+ }
808
+ }
809
+
810
+ function buildActionPayload() {
811
+ const actionType = els.actionType.value;
812
+ const action = { action_type: actionType };
813
+
814
+ if (actionType === "classify" && els.category.value) {
815
+ action.category = els.category.value;
816
+ }
817
+ if (actionType === "lookup_faq" && els.faqId.value) {
818
+ action.faq_id = els.faqId.value;
819
+ }
820
+ if (["ask_clarification", "reply", "escalate"].includes(actionType) && els.message.value.trim()) {
821
+ action.message = els.message.value.trim();
822
+ }
823
+ return { action };
824
+ }
825
+
826
+ async function executeStep() {
827
+ els.stepBtn.disabled = true;
828
+ try {
829
+ const res = await fetch("/step", {
830
+ method: "POST",
831
+ headers: { "Content-Type": "application/json" },
832
+ body: JSON.stringify(buildActionPayload())
833
+ });
834
+ const data = await handleResponse(res);
835
+ state.observation = data.observation;
836
+ state.reward = data.reward;
837
+ state.done = Boolean(data.done);
838
+ state.info = data.info || {};
839
+ updateView();
840
+ } catch (error) {
841
+ alert(`Step failed: ${error.message}`);
842
+ } finally {
843
+ els.stepBtn.disabled = false;
844
+ }
845
+ }
846
+
847
+ populateSelect(els.category, categoryChoices);
848
+ populateSelect(els.faqId, faqChoices);
849
+ updateActionFields();
850
+ updateView();
851
+ checkHealth();
852
+
853
+ els.actionType.addEventListener("change", updateActionFields);
854
+ els.resetBtn.addEventListener("click", resetEnv);
855
+ els.stepBtn.addEventListener("click", executeStep);
856
+ els.stateBtn.addEventListener("click", fetchState);
857
+ </script>
858
+ </body>
859
+ </html>
860
+ """
861
+
862
 
863
  def get_env() -> HelpdeskEnv:
864
  global _env
 
889
  return {"status": "healthy"}
890
 
891
 
892
+ @app.get("/", response_class=HTMLResponse)
893
+ def root() -> HTMLResponse:
894
+ return HTMLResponse(UI_HTML)
 
 
 
 
895
 
896
 
897
  @app.post("/reset")