@peopl-health/nexus 5.56.6 → 5.56.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -15,6 +15,7 @@ const RISK_ASSESSMENT_DEFAULTS = { presetId: '' };
|
|
|
15
15
|
const TRIAGE_GATE_DEFAULTS = { presetId: '' };
|
|
16
16
|
const TRIAGE_PLAN_DEFAULTS = { presetId: '' };
|
|
17
17
|
const ESCALATION_DRAFT_DEFAULTS = { presetId: '' };
|
|
18
|
+
const ESCALATION_QUESTIONS_DEFAULTS = { presetId: '' };
|
|
18
19
|
|
|
19
20
|
const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
|
|
20
21
|
|
|
@@ -56,7 +57,11 @@ async function load() {
|
|
|
56
57
|
if (byKey.ESCALATION_DRAFT && !isPlainObject(parsedEscalationDraft)) throw new Error('subAgents config ESCALATION_DRAFT is not a JSON object');
|
|
57
58
|
const escalationDraft = { ...ESCALATION_DRAFT_DEFAULTS, ...(parsedEscalationDraft || {}) };
|
|
58
59
|
|
|
59
|
-
const
|
|
60
|
+
const parsedEscalationQuestions = safeParse(byKey.ESCALATION_QUESTIONS, null);
|
|
61
|
+
if (byKey.ESCALATION_QUESTIONS && !isPlainObject(parsedEscalationQuestions)) throw new Error('subAgents config ESCALATION_QUESTIONS is not a JSON object');
|
|
62
|
+
const escalationQuestions = { ...ESCALATION_QUESTIONS_DEFAULTS, ...(parsedEscalationQuestions || {}) };
|
|
63
|
+
|
|
64
|
+
const config = { EXTRACTOR: extractor, COMPOSER: composer, PATTERN_CONSULT: patternConsult, RISK_ASSESSMENT: riskAssessment, TRIAGE_GATE: triageGate, TRIAGE_PLAN: triagePlan, ESCALATION_DRAFT: escalationDraft, ESCALATION_QUESTIONS: escalationQuestions };
|
|
60
65
|
cache.set(CACHE_KEY, config);
|
|
61
66
|
return config;
|
|
62
67
|
}
|
|
@@ -73,4 +78,5 @@ module.exports = {
|
|
|
73
78
|
getTriageGate: () => get('TRIAGE_GATE'),
|
|
74
79
|
getTriagePlan: () => get('TRIAGE_PLAN'),
|
|
75
80
|
getEscalationDraft: () => get('ESCALATION_DRAFT'),
|
|
81
|
+
getEscalationQuestions: () => get('ESCALATION_QUESTIONS'),
|
|
76
82
|
};
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
const { getEscalationQuestions } = require('../config/subAgentsConfig');
|
|
2
|
+
|
|
3
|
+
const { readStructuredText } = require('../helpers/structuredTextHelper');
|
|
4
|
+
const { createLLMProvider } = require('../providers/createLLMProvider');
|
|
5
|
+
|
|
6
|
+
const { getEscalationContext } = require('../../services/escalationContextService');
|
|
7
|
+
|
|
8
|
+
const { logger } = require('../../utils/logger');
|
|
9
|
+
const { safeParse } = require('../../utils/jsonUtils');
|
|
10
|
+
const { withTiming } = require('../../utils/tracingDecorator');
|
|
11
|
+
|
|
12
|
+
const CONVERSATION_TURNS = 40;
|
|
13
|
+
const TRIAGE_LIMIT = 3;
|
|
14
|
+
const CALL_LOG_LIMIT = 10;
|
|
15
|
+
const MAX_QUESTIONS = 5;
|
|
16
|
+
const MAX_RED_FLAGS = 4;
|
|
17
|
+
const GRADED_FROM = 2;
|
|
18
|
+
|
|
19
|
+
const trimmed = (value) => String(value ?? '').trim();
|
|
20
|
+
const dayOf = (value) => (value ? String(value).slice(0, 10) : null);
|
|
21
|
+
|
|
22
|
+
function gradedSymptoms(triages, now) {
|
|
23
|
+
const today = dayOf(new Date(now).toISOString());
|
|
24
|
+
return (Array.isArray(triages) ? triages : [])
|
|
25
|
+
.flatMap((triage) => (triage?.symptoms ?? []).map((symptom) => {
|
|
26
|
+
const grade = Math.max(symptom?.gradeNum ?? 0, symptom?.compositeGrade ?? 0);
|
|
27
|
+
return {
|
|
28
|
+
name: symptom?.name ?? null,
|
|
29
|
+
grade,
|
|
30
|
+
reportedTimeFrame: symptom?.reportedTimeFrame ?? null,
|
|
31
|
+
attributes: symptom?.attributes ?? null,
|
|
32
|
+
patientNote: symptom?.patientNote ?? null,
|
|
33
|
+
triagedAt: triage?.created ?? null,
|
|
34
|
+
isToday: dayOf(triage?.created) === today,
|
|
35
|
+
};
|
|
36
|
+
}))
|
|
37
|
+
.filter((symptom) => symptom.grade >= GRADED_FROM)
|
|
38
|
+
.sort((left, right) => Number(right.isToday) - Number(left.isToday) || right.grade - left.grade);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function buildQuestionsInput({ context, callLogs, now }) {
|
|
42
|
+
const conversation = Array.isArray(context?.conversation)
|
|
43
|
+
? context.conversation.slice(-CONVERSATION_TURNS)
|
|
44
|
+
: context?.conversation ?? null;
|
|
45
|
+
const triages = Array.isArray(context?.triages) ? context.triages.slice(0, TRIAGE_LIMIT) : [];
|
|
46
|
+
|
|
47
|
+
return {
|
|
48
|
+
now: new Date(now).toISOString(),
|
|
49
|
+
limits: { questions: MAX_QUESTIONS, redFlags: MAX_RED_FLAGS },
|
|
50
|
+
patient: {
|
|
51
|
+
clinicalContext: context?.agentContext ?? null,
|
|
52
|
+
conversation,
|
|
53
|
+
triages,
|
|
54
|
+
carePlan: context?.carePlan ?? null,
|
|
55
|
+
history: context?.history ?? null,
|
|
56
|
+
},
|
|
57
|
+
gradedSymptoms: gradedSymptoms(triages, now),
|
|
58
|
+
call: (callLogs ?? []).slice(-CALL_LOG_LIMIT).map((log) => ({
|
|
59
|
+
outcome: log?.outcome ?? null,
|
|
60
|
+
notes: trimmed(log?.notes) || null,
|
|
61
|
+
calledAt: log?.calledAt ?? null,
|
|
62
|
+
})),
|
|
63
|
+
sectionsUnavailable: context?.degradedSections ?? [],
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function questionsProvider() {
|
|
68
|
+
try {
|
|
69
|
+
return createLLMProvider({ variant: 'anthropic' });
|
|
70
|
+
} catch (error) {
|
|
71
|
+
logger.warn('[escalationQuestions] no provider available; not generating', { error: error.message });
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const shortList = (value, limit) => (Array.isArray(value) ? value : [])
|
|
77
|
+
.map((entry) => trimmed(entry))
|
|
78
|
+
.filter(Boolean)
|
|
79
|
+
.slice(0, limit);
|
|
80
|
+
|
|
81
|
+
async function generateKeyQuestions({ code, callLogs = [], provider, trace = null, reviewId = null, now = Date.now() } = {}) {
|
|
82
|
+
const { presetId } = await getEscalationQuestions();
|
|
83
|
+
const llm = provider ?? questionsProvider();
|
|
84
|
+
|
|
85
|
+
if (!presetId || !llm?.runStructured) {
|
|
86
|
+
return { completed: false, configured: false, reason: 'key question generation is not configured' };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const context = await getEscalationContext({ code, now });
|
|
90
|
+
const input = buildQuestionsInput({ context, callLogs, now });
|
|
91
|
+
|
|
92
|
+
let result;
|
|
93
|
+
let durationMs;
|
|
94
|
+
try {
|
|
95
|
+
({ result, durationMs } = await withTiming(() => llm.runStructured({
|
|
96
|
+
presetId,
|
|
97
|
+
input: [{ role: 'user', content: JSON.stringify(input) }],
|
|
98
|
+
metadata: { generator: 'escalation-questions', reviewId: reviewId ?? undefined },
|
|
99
|
+
})));
|
|
100
|
+
} catch (error) {
|
|
101
|
+
logger.error('[escalationQuestions] the provider failed', { error: error.message, reviewId });
|
|
102
|
+
return { completed: false, attempted: true, reason: 'the model could not be reached' };
|
|
103
|
+
}
|
|
104
|
+
trace?.addSubCall({ response: result, durationMs, presetId });
|
|
105
|
+
|
|
106
|
+
if (result?.status && result.status !== 'completed') {
|
|
107
|
+
logger.warn('[escalationQuestions] generation did not complete', { status: result.status, reviewId });
|
|
108
|
+
return { completed: false, attempted: true, reason: `generation incomplete: status=${result.status}` };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const parsed = safeParse(readStructuredText(result), null);
|
|
112
|
+
const questions = shortList(parsed?.questions, MAX_QUESTIONS);
|
|
113
|
+
const redFlags = shortList(parsed?.redFlags, MAX_RED_FLAGS);
|
|
114
|
+
|
|
115
|
+
if (!questions.length) {
|
|
116
|
+
logger.warn('[escalationQuestions] generation returned no questions', { reviewId });
|
|
117
|
+
return { completed: false, attempted: true, reason: 'the model returned no questions' };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
completed: true,
|
|
122
|
+
attempted: true,
|
|
123
|
+
questions,
|
|
124
|
+
redFlags,
|
|
125
|
+
gradedSymptoms: input.gradedSymptoms,
|
|
126
|
+
sectionsUnavailable: context.degradedSections ?? [],
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
module.exports = { generateKeyQuestions, buildQuestionsInput, gradedSymptoms, MAX_QUESTIONS, MAX_RED_FLAGS };
|
|
@@ -14,6 +14,7 @@ const {
|
|
|
14
14
|
sendApprovedIndications,
|
|
15
15
|
setReviewCases,
|
|
16
16
|
suggestDraft,
|
|
17
|
+
suggestKeyQuestions,
|
|
17
18
|
syncEscalationReviewCase,
|
|
18
19
|
} = require('../services/escalationReviewService');
|
|
19
20
|
|
|
@@ -90,6 +91,16 @@ const suggestEscalationReviewDraftController = async (req, res) => {
|
|
|
90
91
|
}
|
|
91
92
|
};
|
|
92
93
|
|
|
94
|
+
const suggestEscalationReviewQuestionsController = async (req, res) => {
|
|
95
|
+
try {
|
|
96
|
+
const { triggeredBy } = req.body || {};
|
|
97
|
+
const questions = await suggestKeyQuestions({ id: req.params.id, requestedBy: triggeredBy, requestId: req.requestId });
|
|
98
|
+
res.status(200).json({ success: true, questions });
|
|
99
|
+
} catch (error) {
|
|
100
|
+
respondWithError(res, error, 'generating escalation review key questions', { reviewId: req.params?.id });
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
93
104
|
const addEscalationReviewDraftController = async (req, res) => {
|
|
94
105
|
try {
|
|
95
106
|
const { doctorText, patientMessage, triggeredBy } = req.body || {};
|
|
@@ -206,5 +217,6 @@ module.exports = {
|
|
|
206
217
|
sendEscalationReviewIndicationsController,
|
|
207
218
|
setEscalationReviewCasesController,
|
|
208
219
|
suggestEscalationReviewDraftController,
|
|
220
|
+
suggestEscalationReviewQuestionsController,
|
|
209
221
|
syncEscalationReviewCaseController,
|
|
210
222
|
};
|
package/lib/routes/index.js
CHANGED
|
@@ -123,6 +123,7 @@ const escalationReviewRouteDefinitions = {
|
|
|
123
123
|
'POST /:id/cases': 'setEscalationReviewCasesController',
|
|
124
124
|
'POST /:id/call-logs': 'addEscalationReviewCallLogController',
|
|
125
125
|
'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
|
|
126
|
+
'POST /:id/key-questions': 'suggestEscalationReviewQuestionsController',
|
|
126
127
|
'POST /:id/drafts': 'addEscalationReviewDraftController',
|
|
127
128
|
'POST /:id/doctor-handoffs': 'handOffEscalationReviewController',
|
|
128
129
|
'POST /:id/decisions': 'recordEscalationReviewDecisionController',
|
|
@@ -285,6 +286,7 @@ const builtInControllers = {
|
|
|
285
286
|
setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
|
|
286
287
|
addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
|
|
287
288
|
suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
|
|
289
|
+
suggestEscalationReviewQuestionsController: escalationReviewController.suggestEscalationReviewQuestionsController,
|
|
288
290
|
addEscalationReviewDraftController: escalationReviewController.addEscalationReviewDraftController,
|
|
289
291
|
handOffEscalationReviewController: escalationReviewController.handOffEscalationReviewController,
|
|
290
292
|
recordEscalationReviewDecisionController: escalationReviewController.recordEscalationReviewDecisionController,
|
|
@@ -18,6 +18,7 @@ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
|
18
18
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
19
19
|
const { sendMessage } = require('../core/NexusMessaging');
|
|
20
20
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
21
|
+
const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
|
|
21
22
|
|
|
22
23
|
const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
23
24
|
const { getPatientTasks, updatePatientTask } = require('./patientTaskService');
|
|
@@ -586,6 +587,27 @@ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
|
|
|
586
587
|
return draft;
|
|
587
588
|
}
|
|
588
589
|
|
|
590
|
+
async function suggestKeyQuestions({ id, requestedBy, requestId = null } = {}) {
|
|
591
|
+
const reviewId = reviewIdOf(id);
|
|
592
|
+
const operator = requiredText(requestedBy, 'requestedBy');
|
|
593
|
+
const review = await loadReview(reviewId);
|
|
594
|
+
if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
|
|
595
|
+
|
|
596
|
+
const generated = await generateKeyQuestions({
|
|
597
|
+
code: review.patientCode,
|
|
598
|
+
callLogs: review.callLogs ?? [],
|
|
599
|
+
reviewId: String(review._id),
|
|
600
|
+
});
|
|
601
|
+
if (generated.attempted) {
|
|
602
|
+
await audit(review, operator, requestId, generated.completed
|
|
603
|
+
? { action: 'key_questions_generated' }
|
|
604
|
+
: { action: 'key_questions_generation_failed', reason: redactedError({ message: generated.reason }) });
|
|
605
|
+
}
|
|
606
|
+
if (!generated.completed) throw httpError(generated.configured === false ? 503 : 502, generated.reason);
|
|
607
|
+
|
|
608
|
+
return generated;
|
|
609
|
+
}
|
|
610
|
+
|
|
589
611
|
async function addDraft({ id, doctorText, patientMessage, writtenBy, requestId = null } = {}) {
|
|
590
612
|
const reviewId = reviewIdOf(id);
|
|
591
613
|
const operator = requiredText(writtenBy, 'writtenBy');
|
|
@@ -859,5 +881,6 @@ module.exports = {
|
|
|
859
881
|
sendApprovedIndications,
|
|
860
882
|
setReviewCases,
|
|
861
883
|
suggestDraft,
|
|
884
|
+
suggestKeyQuestions,
|
|
862
885
|
syncEscalationReviewCase,
|
|
863
886
|
};
|