Repository navigation
Expand file tree
/
Copy pathmultimode-interface.html
More file actions
4660 lines (4351 loc) · 287 KB
/
Copy pathmultimode-interface.html
File metadata and controls
4660 lines (4351 loc) · 287 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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>myGov - Multi-Mode Interface</title>
<!-- Material-UI -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
<!-- React & Dependencies -->
<script
crossorigin
src="https://unpkg.com/react@18/umd/react.production.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/@mui/material@5.14.0/umd/material-ui.production.min.js"
></script>
<script
crossorigin
src="https://unpkg.com/@babel/standalone/babel.min.js"
></script>
<!-- D3.js for Journey visualization -->
<script src="https://d3js.org/d3.v7.min.js"></script>
<!-- Local fallback graph data (used if API not available) -->
<script src="data/lifevents-graph.js"></script>
<style>
body {
margin: 0;
font-family: "Roboto", sans-serif;
background-color: #f5f5f5;
}
.chat-messages {
height: 400px;
overflow-y: auto;
padding: 16px;
background-color: #fafafa;
border-radius: 4px;
margin-bottom: 16px;
}
.chat-message {
margin-bottom: 16px;
display: flex;
align-items: flex-start;
gap: 8px;
}
.chat-message.user {
flex-direction: row-reverse;
}
.chat-bubble {
max-width: 70%;
padding: 12px 16px;
border-radius: 16px;
background-color: #e0e0e0;
}
.chat-message.user .chat-bubble {
background-color: #1976d2;
color: white;
}
.chat-avatar {
width: 36px;
height: 36px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 14px;
font-weight: 500;
}
.chat-message.assistant .chat-avatar {
background-color: #66d3ee;
color: #333;
}
.chat-message.user .chat-avatar {
background-color: #1976d2;
color: white;
}
.chat-message.system {
justify-content: center;
}
.chat-message.system .chat-avatar {
background-color: #ff9800;
color: white;
font-size: 12px;
}
.chat-message.system .chat-bubble {
background-color: #fff3e0;
border: 1px solid #ffcc02;
color: #ef6c00;
font-style: italic;
font-size: 14px;
}
/* Markdown styling within chat messages */
.chat-bubble strong {
font-weight: 600;
}
.chat-bubble em {
font-style: italic;
}
.chat-bubble a {
color: inherit;
text-decoration: underline;
text-underline-offset: 2px;
}
.chat-bubble.user a {
color: #e3f2fd;
}
.chat-bubble code {
background-color: rgba(0, 0, 0, 0.1);
padding: 2px 4px;
border-radius: 3px;
font-family: 'Courier New', monospace;
font-size: 0.9em;
}
.chat-bubble.user code {
background-color: rgba(255, 255, 255, 0.2);
}
.content-section {
margin-bottom: 32px;
}
.content-card {
transition: transform 0.2s;
}
.content-card:hover {
transform: translateY(-2px);
}
.filter-chips {
display: flex;
gap: 8px;
flex-wrap: wrap;
margin-bottom: 16px;
}
.logo-container {
display: flex;
align-items: center;
gap: 12px;
}
.logo-image {
height: 40px;
width: auto;
}
@media print {
.MuiAppBar-root,
.MuiBottomNavigation-root {
display: none !important;
}
}
</style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
const {
AppBar,
Toolbar,
Typography,
Container,
Box,
Card,
CardContent,
Button,
IconButton,
TextField,
Chip,
Paper,
Grid,
List,
ListItem,
ListItemText,
ListItemIcon,
Checkbox,
Accordion,
AccordionSummary,
AccordionDetails,
Badge,
LinearProgress,
ToggleButton,
ToggleButtonGroup,
Slider,
Tabs,
Tab,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Menu,
MenuItem,
Snackbar,
Alert,
Divider,
InputAdornment,
Select,
InputLabel,
Radio,
RadioGroup,
FormControlLabel,
FormControl,
FormLabel,
FormGroup,
Avatar,
Stack,
Fade,
Grow,
Collapse,
CircularProgress,
Link,
} = MaterialUI;
// Icons
const SettingsIcon = () => (
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
<path d="M19.14 12.94c.04-.31.06-.63.06-.94 0-.31-.02-.63-.06-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.04.31-.06.63-.06.94s.02.63.06.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z"/>
</svg>
);
const { useState, useEffect, useRef, useCallback } = React;
// API Configuration
const API_BASE_URL = location.protocol.startsWith("http")
? location.origin
: "http://localhost:3000";
const MCP_BASE_URL = location.protocol.startsWith("http")
? `${location.protocol}//${location.hostname}:8081`
: "http://localhost:8081";
const API_ENDPOINTS = {
search: `${API_BASE_URL}/api/fragments/search`,
facets: `${API_BASE_URL}/api/fragments/facets`,
ollama: `${API_BASE_URL}/api/ollama/chat`,
llm: `${API_BASE_URL}/api/llm/chat`,
llmWithContext: `${API_BASE_URL}/api/llm/chat-with-context`,
llmModels: `${API_BASE_URL}/api/llm/models`,
// Journey/Profile endpoints
journeyBuild: `${API_BASE_URL}/api/journey/profile/build`,
journeyData: (id) => `${API_BASE_URL}/api/journey/journey/${id}`,
journeyViz: (id) => `${API_BASE_URL}/api/journey/journey/${id}/visualization`,
};
// Host configuration - stored in localStorage, user-configurable
// Default: exclude analysis-only hosts, but user can enable them
const DEFAULT_EXCLUDED_HOSTS = [
'centrelink.gov.au',
'operational.servicesaustralia.gov.au',
'medicare.gov.au',
'csda.gov.au'
];
// Load excluded hosts from localStorage or use defaults
const getStoredExcludedHosts = () => {
try {
const stored = localStorage.getItem('excludedHosts');
if (stored) return JSON.parse(stored);
} catch (e) {}
return DEFAULT_EXCLUDED_HOSTS;
};
// Global mutable ref for excluded hosts (updated by config modal)
let currentExcludedHosts = getStoredExcludedHosts();
// Helper to filter out excluded hosts from results
const filterExcludedHosts = (results) => {
if (!results || !Array.isArray(results)) return results;
return results.filter(item => {
const url = item.url || item.document?.url || '';
try {
const host = new URL(url).hostname;
return !currentExcludedHosts.some(excluded => host.includes(excluded));
} catch {
return true; // Keep items with invalid URLs
}
});
};
// Category to Life Event mappings - FIXED TO MATCH ACTUAL API DATA
const categoryToLifeEvents = {
"Health and caring": [
"Seeking medical help",
"Being diagnosed with a medical condition or disability",
"Experiencing mental illness",
"Being seriously injured",
"Providing temporary care for another",
"Becoming a long term carer",
"Ceasing to be a carer",
"Experiencing the death of a loved one",
"Coming to the end of your life",
"Becoming an older Australian",
"Accessing aged care",
],
"Family and Relationships": [
"Getting together",
"Making it work",
"Breaking up",
"Having a baby",
"Adopting a child",
"Fostering a child",
"Raising a child to adulthood",
"Separated parents",
"Estrangement from family",
"Getting a pet",
],
"Work and Money": [
// Fixed capitalization
"Working",
"Changing careers",
"Returning to work",
"Experiencing workplace conflict",
"Becoming unemployed",
"Looking for work",
"Retiring from the workforce",
"Starting a business",
"Establishing trade",
"Growing a business",
"Having a business fail",
"Closing a business",
"Selling a business",
"Experiencing financial stress",
],
"Housing and Travel": [
// Fixed capitalization
"Coming to Australia to visit",
"Moving to Australia permanently",
"Coming to Australia as a refugee",
"Renting a home",
"Buying a home",
"Moving into an existing household",
"Experiencing homelessness",
"Moving domestically",
"Moving abroad",
"Travelling within Australia",
"Travelling overseas",
],
"Disasters and Crime": [
// Fixed capitalization
"Being the victim of a crime",
"Being arrested and charged with a crime",
"Being involved in a lawsuit",
"Being sentenced and serving your sentence",
"Being released from prison",
"Experiencing domestic violence",
"Leaving a violent relationship",
"Being removed from your family",
"Experiencing a war",
"Experiencing terrorist act",
"Experiencing a major industrial accident",
"Experiencing a pandemic",
"Experiencing a sudden disaster",
"Experiencing a gradual disaster",
],
"Education and Identity": [
// Fixed capitalization
"Becoming a driver",
"Becoming financially independent",
"Moving out of home for the first time",
"Coming out",
"Changing gender identity",
"Changing national identity",
"Change in religious beliefs",
"Transitioning to civilian life",
"Studying at primary school",
"Studying at high school",
"Studying at a tertiary institution",
"Becoming an apprentice",
"Upgrading professional skills or qualifications",
"Coming to Australia temporarily",
],
};
function App() {
const [mode, setMode] = useState("guided"); // browse, home, search, chat, guided
const [expandedAccordions, setExpandedAccordions] = useState(new Set());
// Handle accordion toggle
const handleAccordionToggle = (accordionId) => {
setExpandedAccordions(prev => {
const newSet = new Set(prev);
if (newSet.has(accordionId)) {
newSet.delete(accordionId);
} else {
newSet.add(accordionId);
}
return newSet;
});
};
const [facetsData, setFacetsData] = useState(null);
const [results, setResults] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
// Host configuration state
const [configOpen, setConfigOpen] = useState(false);
const [availableHosts, setAvailableHosts] = useState([]);
const [excludedHosts, setExcludedHosts] = useState(getStoredExcludedHosts());
// Known available hosts (from Typesense index)
const KNOWN_HOSTS = [
{ value: 'operational.servicesaustralia.gov.au', count: 17679, label: 'Operational Blueprint' },
{ value: 'my.gov.au', count: 510, label: 'myGov' },
{ value: 'www.servicesaustralia.gov.au', count: 100, label: 'Services Australia' },
{ value: 'centrelink.gov.au', count: 1, label: 'Centrelink (legacy)' }
];
// Set available hosts on mount
useEffect(() => {
setAvailableHosts(KNOWN_HOSTS);
}, []);
// Update excluded hosts and persist
const updateExcludedHosts = (newExcluded) => {
setExcludedHosts(newExcluded);
currentExcludedHosts = newExcluded; // Update global ref for filter function
try {
localStorage.setItem('excludedHosts', JSON.stringify(newExcluded));
} catch (e) {}
};
// Selection state
const [selections, setSelections] = useState({
category: null,
lifeEvent: null,
provider: null,
});
// Search state
const [searchQuery, setSearchQuery] = useState("");
const [searchFilters, setSearchFilters] = useState({
category: null,
lifeEvent: null,
provider: null,
state: null,
});
// Chat state
const [chatMessages, setChatMessages] = useState([
{
type: "assistant",
text: "Hello! I'm here to help you find government services. What can I help you with today?",
},
]);
const [chatInput, setChatInput] = useState("");
const [ollamaModel, setOllamaModel] = useState("gemma3:27b"); // Legacy - kept for backward compat
const [llmModel, setLlmModel] = useState("bedrock:mistral.mistral-large-2402-v1:0");
const [availableModels, setAvailableModels] = useState([]);
// Load available LLM models from API
const [modelStatus, setModelStatus] = useState(null);
const [modelRecommendations, setModelRecommendations] = useState(null);
const [loadingModels, setLoadingModels] = useState(false);
// AI Summary state
const [aiSummary, setAiSummary] = useState(null);
const [loadingSummary, setLoadingSummary] = useState(false);
// AI Reordering state
const [reorderedResults, setReorderedResults] = useState(null);
const [loadingReorder, setLoadingReorder] = useState(false);
// Shared Profile state (persisted across modes)
const defaultProfile = () => ({
id: "user_" + Date.now(),
name: "Guest User",
age: null,
income: null,
citizenship: ["Australian"],
residency_state: "National",
employment_status: null,
housing_status: null,
has_children: false,
children: [],
is_carer: false,
has_disability: false,
current_life_events: [],
completed_life_events: [],
marital_status: null,
study_status: null,
level: 1,
experience_points: 0,
});
const [userProfile, setUserProfile] = useState(() => {
try {
const stored = localStorage.getItem('userProfile');
return stored ? JSON.parse(stored) : defaultProfile();
} catch (e) {
return defaultProfile();
}
});
const [profileId, setProfileId] = useState(null);
const [profileApiError, setProfileApiError] = useState(null);
const [guidedChatMessages, setGuidedChatMessages] = useState([]);
const [guidedChatInput, setGuidedChatInput] = useState("");
const [currentQuestion, setCurrentQuestion] = useState(0);
const [isProfileComplete, setIsProfileComplete] = useState(false);
const [matchedServices, setMatchedServices] = useState([]);
const [loadingServices, setLoadingServices] = useState(false);
// Chat: use local profile toggle
const [useProfileForChat, setUseProfileForChat] = useState(() => {
try { return JSON.parse(localStorage.getItem('useProfileForChat') || 'true'); } catch { return true; }
});
useEffect(() => {
try { localStorage.setItem('useProfileForChat', JSON.stringify(useProfileForChat)); } catch {}
}, [useProfileForChat]);
// Journey visualization state/refs
const journeyMapRef = useRef(null);
const journeyFitRef = useRef(null);
const journeyGraphMapRef = useRef({ indexById: new Map(), nodes: [] });
const rebuildGraphRef = useRef(null);
const [selectedEvent, setSelectedEvent] = useState(null);
const [journeyVizData, setJourneyVizData] = useState(null);
// Persist profile and sync to server recommender
const buildServerProfile = async (p) => {
try {
const resp = await fetch(API_ENDPOINTS.journeyBuild, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(p)
});
if (!resp.ok) throw new Error(await resp.text());
const data = await resp.json();
setProfileId(data.profile_id || null);
setProfileApiError(null);
} catch (e) {
console.warn('Profile build failed:', e.message);
setProfileApiError('Recommender API unavailable — using local fallback.');
}
};
useEffect(() => {
try { localStorage.setItem('userProfile', JSON.stringify(userProfile)); } catch (e) {}
buildServerProfile(userProfile);
}, [userProfile]);
// Function to parse markdown to HTML
const parseMarkdown = (text) => {
if (!text) return '';
return text
// Bold text
.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
// Italic text
.replace(/\*(.*?)\*/g, '<em>$1</em>')
// Links
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>')
// Line breaks
.replace(/\n/g, '<br>')
// Code inline
.replace(/`([^`]+)`/g, '<code>$1</code>');
};
const loadModels = async () => {
setLoadingModels(true);
try {
const resp = await fetch(API_ENDPOINTS.llmModels);
if (resp.ok) {
const data = await resp.json();
const list = data.models || [];
setAvailableModels(list);
setModelStatus(data.status);
setModelRecommendations(data.recommendations);
// Select first available model if current is unavailable
const currentModel = list.find(m => m.value === llmModel);
if (!currentModel || currentModel.status !== 'available') {
const availableModel = list.find(m => m.status === 'available');
if (availableModel) {
setLlmModel(availableModel.value);
} else if (list.length > 0) {
setLlmModel(list[0].value);
}
}
} else {
throw new Error("Failed to load models");
}
} catch (e) {
console.warn("Falling back to default model list:", e.message);
const fallback = [
{
value: "bedrock:anthropic.claude-3-sonnet-20240229-v1:0",
label: "Bedrock • Claude 3 Sonnet",
provider: "bedrock",
status: "available"
}
];
setAvailableModels(fallback);
setError("Could not load available models. Using default.");
} finally {
setLoadingModels(false);
}
};
useEffect(() => {
loadModels();
}, []);
// Generate AI summary for search results
const generateSummary = async (searchResults) => {
if (!searchResults || searchResults.length === 0 || !llmModel) return;
setLoadingSummary(true);
try {
// Prepare content for summarization
const resultsText = searchResults.map(result =>
`Title: ${result.document.title}\n` +
`Provider: ${result.document.provider || 'N/A'}\n` +
`Content: ${result.document.content_text || 'No content'}\n` +
`URL: ${result.document.url}`
).join('\n\n---\n\n');
const summaryPrompt = `Please provide a concise summary of these search results. Focus on:
1. What types of information/services are covered
2. Key themes or topics
3. Which government providers are involved
4. Any patterns or connections between results
IMPORTANT: Only summarize what is provided - do not add any new information or recommendations.
Search Results:
${resultsText}`;
const response = await fetch(API_ENDPOINTS.llm, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
model: llmModel,
prompt: summaryPrompt,
}),
});
const data = await response.json();
if (response.ok) {
setAiSummary(data.response);
} else {
console.error('Summary generation failed:', data.error);
}
} catch (error) {
console.error('Summary generation error:', error);
} finally {
setLoadingSummary(false);
}
};
// Reorder content for better reading flow (Home page)
const reorderContentForFlow = async (contentResults) => {
if (!contentResults || contentResults.length === 0 || !llmModel) return;
setLoadingReorder(true);
try {
// Prepare content list with IDs and titles
const contentList = contentResults.map((result, index) => ({
id: result.id,
index: index,
title: result.title,
description: result.description || '',
category: result.category,
life_event: result.lifeEvent || result.life_event || 'General',
provider: result.provider,
state: result.state || 'National',
hierarchy: result.hierarchy || result.hierarchy_lvl0 || '',
relevance_score: typeof result.relevance_score === 'number' ? result.relevance_score : 0.5
}));
const reorderPrompt = `You are helping organize government information for better reading flow.
Given the following content fragments, reorder them to create a more logical and cohesive reading experience.
IMPORTANT RULES:
1. You MUST return ONLY a JSON array of indices in the new order
2. You MUST use every index exactly once (no additions, no removals)
3. Primary ordering key is higher "relevance_score" first (descending)
4. Consider logical flow: general info → specific services → forms/applications → additional resources
5. Group related topics together
6. Prefer state-specific and provider-specific content before general content when relevant
7. If two fragments are near-duplicates (same title or same URL), keep only the one that best fits the flow; place duplicates adjacent at the end of the list (to be filtered out by the caller)
5. DO NOT generate any new content or explanations
Content fragments:
${JSON.stringify(contentList, null, 2)}
Return ONLY a JSON array of the indices in the optimal reading order, like: [2, 0, 1, 3, ...]`;
const response = await fetch(API_ENDPOINTS.llm, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
model: llmModel,
prompt: reorderPrompt,
}),
});
const data = await response.json();
if (response.ok) {
try {
// Extract JSON array from response (handle if model adds extra text)
const responseText = data.response;
const jsonMatch = responseText.match(/\[[\d,\s]+\]/);
if (jsonMatch) {
const newOrder = JSON.parse(jsonMatch[0]);
// Validate the order array
if (Array.isArray(newOrder) &&
newOrder.length === contentResults.length &&
new Set(newOrder).size === newOrder.length) {
// Reorder the results based on AI suggestion
const reordered = newOrder.map(index => contentResults[index]);
setReorderedResults(reordered);
return reordered;
}
}
} catch (parseError) {
console.error('Failed to parse reorder response:', parseError);
}
}
} catch (error) {
console.error('Content reordering error:', error);
} finally {
setLoadingReorder(false);
}
return null; // Return null if reordering fails
};
// Profile Building Questions
const profileQuestions = [
{
id: 'age',
question: "Hi! I'm here to help you find the government services you're eligible for. Let's start with some basic information. How old are you?",
type: 'number',
field: 'age',
validation: (value) => value > 0 && value < 120,
followUp: (age) => age < 25 ? "Great! There are specific services available for young people." : age >= 67 ? "There are specific services for older Australians." : "Thanks!"
},
{
id: 'employment',
question: "What's your current employment status?",
type: 'choice',
field: 'employment_status',
options: [
{ value: 'employed', label: 'Employed full-time' },
{ value: 'part_time', label: 'Employed part-time' },
{ value: 'casual', label: 'Casual employment' },
{ value: 'unemployed', label: 'Unemployed/Looking for work' },
{ value: 'student', label: 'Student' },
{ value: 'retired', label: 'Retired' },
{ value: 'self_employed', label: 'Self-employed' },
{ value: 'unable_to_work', label: 'Unable to work due to illness/disability' }
]
},
{
id: 'income',
question: "What's your approximate annual income before tax? (You can skip this if you prefer)",
type: 'number',
field: 'income',
optional: true,
prefix: '$',
followUp: (income) => income && income < 30000 ? "You may be eligible for low-income support services." : ""
},
{
id: 'housing',
question: "What's your housing situation?",
type: 'choice',
field: 'housing_status',
options: [
{ value: 'owner', label: "I own my home" },
{ value: 'buying', label: "I'm paying off a mortgage" },
{ value: 'renting_private', label: 'Renting privately' },
{ value: 'renting_public', label: 'Public/social housing' },
{ value: 'staying_with_others', label: 'Staying with family/friends' },
{ value: 'homeless', label: 'No fixed address/experiencing homelessness' }
]
},
{
id: 'family',
question: "Do you have children under 18 living with you?",
type: 'boolean',
field: 'has_children',
followUpQuestion: {
condition: true,
question: "How many children do you have?",
type: 'number',
field: 'children_count'
}
},
{
id: 'carer',
question: "Are you a carer for someone (like a family member with disability, illness, or an elderly person)?",
type: 'boolean',
field: 'is_carer',
followUp: (isCarer) => isCarer ? "There are specific support services available for carers." : ""
},
{
id: 'disability',
question: "Do you have a disability or long-term health condition that affects your daily life?",
type: 'boolean',
field: 'has_disability',
followUp: (hasDisability) => hasDisability ? "There are support services and payments available for people with disabilities." : ""
},
{
id: 'life_events',
question: "Are you currently experiencing any of these life events?",
type: 'multiple_choice',
field: 'current_life_events',
options: [
{ value: 'having_baby', label: 'Having a baby' },
{ value: 'relationship_change', label: 'Relationship breakdown/divorce' },
{ value: 'job_loss', label: 'Lost my job recently' },
{ value: 'starting_work', label: 'Starting a new job' },
{ value: 'moving_house', label: 'Moving house' },
{ value: 'studying', label: 'Starting or continuing studies' },
{ value: 'health_change', label: 'Significant health change' },
{ value: 'domestic_violence', label: 'Experiencing domestic violence' },
{ value: 'none', label: 'None of these apply to me' }
]
}
];
// Initialize chat with first question
useEffect(() => {
if (mode === "guided" && guidedChatMessages.length === 0) {
setGuidedChatMessages([{
type: 'assistant',
text: profileQuestions[0].question,
id: `msg-${Date.now()}`
}]);
}
}, [mode]);
// Handle chat responses and profile building
const handleChatResponse = (response) => {
const question = profileQuestions[currentQuestion];
if (!question) return;
// Add user message
const userMessage = {
type: 'user',
text: response,
id: `msg-${Date.now()}`
};
// Update profile
const updatedProfile = { ...userProfile };
if (question.type === 'choice' || question.type === 'boolean') {
updatedProfile[question.field] = response;
} else if (question.type === 'number') {
updatedProfile[question.field] = parseInt(response);
} else if (question.type === 'multiple_choice') {
updatedProfile[question.field] = Array.isArray(response) ? response : [response];
}
setUserProfile(updatedProfile);
// Generate assistant response
let assistantText = "";
if (question.followUp && typeof question.followUp === 'function') {
assistantText = question.followUp(response);
}
// Move to next question
const nextQuestionIndex = currentQuestion + 1;
if (nextQuestionIndex < profileQuestions.length) {
if (assistantText) {
assistantText += " ";
}
assistantText += profileQuestions[nextQuestionIndex].question;
setCurrentQuestion(nextQuestionIndex);
} else {
// Profile complete
if (assistantText) {
assistantText += " ";
}
assistantText += "Perfect! I've gathered all the information I need. Let me find services that match your situation...";
setIsProfileComplete(true);
setTimeout(() => matchServices(updatedProfile), 1000);
}
const assistantMessage = {
type: 'assistant',
text: assistantText,
id: `msg-${Date.now() + 1}`
};
setGuidedChatMessages(prev => [...prev, userMessage, assistantMessage]);
};
// Match services based on profile
const matchServices = async (profile) => {
setLoadingServices(true);
// Build broader category-based search criteria (more flexible approach)
const relevantCategories = new Set();
// Age-based categories
if (profile.age < 25) {
relevantCategories.add("Education and identity");
relevantCategories.add("Work and Money");
} else if (profile.age >= 67) {
relevantCategories.add("Health and caring");
}
// Employment-based categories
if (profile.employment_status === 'unemployed' || profile.employment_status === 'student') {
relevantCategories.add("Work and Money");
}
// Family-based categories
if (profile.has_children) {
relevantCategories.add("Family and Relationships");
}
// Housing-based categories
if (profile.housing_status === 'homeless' || profile.housing_status === 'renting_private') {
relevantCategories.add("Housing and Travel");
}
// Disability/health-based categories
if (profile.has_disability) {
relevantCategories.add("Health and caring");
}
// Carer-based categories
if (profile.is_carer) {
relevantCategories.add("Health and caring");
relevantCategories.add("Family and Relationships");
}
// Life event categories
if (profile.current_life_events && profile.current_life_events.length > 0) {
profile.current_life_events.forEach(event => {
if (event === 'having_baby') {
relevantCategories.add("Family and Relationships");
} else if (event === 'job_loss' || event === 'starting_work') {
relevantCategories.add("Work and Money");
} else if (event === 'health_change') {
relevantCategories.add("Health and caring");
} else if (event === 'moving_house') {
relevantCategories.add("Housing and Travel");
} else if (event === 'studying') {
relevantCategories.add("Education and identity");
} else if (event === 'relationship_change') {
relevantCategories.add("Family and Relationships");
}
});
}
// If no specific criteria, include basic categories everyone might need
if (relevantCategories.size === 0) {
relevantCategories.add("Health and caring");
relevantCategories.add("Work and Money");
}
// Search for services in each relevant category
let allServices = [];
try {
for (const category of Array.from(relevantCategories)) {
const params = new URLSearchParams({
q: "*",
include_html: "true",
per_page: "15", // Get more results per category
});
params.append("category", category);
const response = await fetch(`${API_ENDPOINTS.search}?${params}`);
if (response.ok) {
const data = await response.json();
console.log(`Search results for category "${category}":`, data.found, 'results found');
if (data.results) {
// Filter excluded hosts and process each result with eligibility scoring
const filteredHits = filterExcludedHosts(data.results.map(h => ({ url: h.document?.url, ...h }))).map(h => ({ document: h.document || h }));
const processedResults = filteredHits.map((hit) => ({
id: hit.document.id,
url: hit.document.url,
title: hit.document.title,
description: hit.document.content_text,
content_html: hit.document.content_html,
category: hit.document.categories?.[0] || category,
lifeEvent: hit.document.life_events?.[0] || "General",
provider: hit.document.provider || "Services Australia",
state: hit.document.states?.[0] || "National",
document: hit.document,
// Add eligibility scoring