Skip to content

Commit 8115a3e

Browse files
committed
Enhance medical document processing by adding trusted medical sources for analysis and improving error handling in the review process. Update Perplexity service to include a new method for verifying medical document analyses against authoritative sources. Ensure all user-facing text is internationalized.
1 parent 96e678a commit 8115a3e

File tree

3 files changed

+102
-9
lines changed

3 files changed

+102
-9
lines changed

backend/src/document-processor/services/aws-bedrock.service.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,18 @@ Look for and extract the following information:
5656
5757
This document may be a lab report showing blood work or other test results, so please pay special attention to tables, numeric values, reference ranges, and medical terminology.
5858
59+
IMPORTANT: Base your analysis on information from multiple trusted medical sources and authorities, including but not limited to:
60+
- Mayo Clinic
61+
- Cleveland Clinic
62+
- CDC (Centers for Disease Control and Prevention)
63+
- NIH (National Institutes of Health)
64+
- WHO (World Health Organization)
65+
- American Medical Association
66+
- American Heart Association
67+
- American Academy of Pediatrics
68+
- UpToDate
69+
- MedlinePlus
70+
5971
Format the response as a JSON object with the following structure:
6072
{
6173
"title": string,
@@ -88,6 +100,7 @@ When extracting lab values:
88100
4. Set "isCritical" to true when the value indicates an urgent medical situation. Set it to false for values that are normal or only slightly abnormal.
89101
5. Include a "conclusion" field that provides a brief interpretation of what this value indicates about the patient's health
90102
6. Include a "suggestions" field that provides brief recommendations based on this value
103+
7. IMPORTANT: If reference ranges are missing from the document, add "reference-ranges-missing" to the missingInformation array in metadata, and use standard reference ranges from trusted medical sources to determine the status.
91104
92105
EXTREMELY IMPORTANT FORMATTING INSTRUCTIONS:
93106
1. ABSOLUTELY DO NOT START YOUR RESPONSE WITH ANY TEXT. Begin immediately with the JSON object.

backend/src/document-processor/services/document-processor.service.ts

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,12 +55,31 @@ export class DocumentProcessorService {
5555
});
5656

5757
// Step 2: Analyze extracted text using AWS Bedrock
58-
const analysis = await this.bedrockService.analyzeMedicalDocument(
58+
const initialAnalysis = await this.bedrockService.analyzeMedicalDocument(
5959
extractedText.rawText,
6060
userId,
6161
);
6262

63-
// Step 3: Generate simplified explanation using Perplexity
63+
// Step 3: Review and verify analysis using Perplexity
64+
this.logger.log('Reviewing medical analysis with Perplexity');
65+
let analysis: MedicalDocumentAnalysis;
66+
67+
try {
68+
const verifiedAnalysis = await this.perplexityService.reviewMedicalAnalysis(
69+
initialAnalysis,
70+
extractedText.rawText,
71+
);
72+
analysis = verifiedAnalysis;
73+
this.logger.log('Analysis verified and possibly corrected by Perplexity');
74+
} catch (reviewError) {
75+
this.logger.error('Error reviewing analysis with Perplexity', {
76+
error: reviewError instanceof Error ? reviewError.message : 'Unknown error',
77+
});
78+
// Fall back to initial analysis if review fails
79+
analysis = initialAnalysis;
80+
}
81+
82+
// Step 4: Generate simplified explanation using Perplexity
6483
let simplifiedExplanation: string | undefined;
6584

6685
try {

backend/src/services/perplexity.service.ts

Lines changed: 68 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -96,13 +96,9 @@ export class PerplexityService {
9696
}
9797

9898
/**
99-
* Sends a chat completion request to the Perplexity API
100-
*
101-
* @param messages Array of messages for the conversation
102-
* @param options Additional options for the request
103-
* @returns The chat completion response
99+
* Queries the Perplexity AI API
104100
*/
105-
async createChatCompletion(
101+
async queryPerplexityAI(
106102
messages: PerplexityMessage[],
107103
options?: {
108104
model?: string;
@@ -163,7 +159,72 @@ export class PerplexityService {
163159
{ role: 'user', content: userPrompt },
164160
];
165161

166-
const response = await this.createChatCompletion(messages);
162+
const response = await this.queryPerplexityAI(messages);
167163
return response.choices[0].message.content.trim();
168164
}
165+
166+
/**
167+
* Reviews and verifies a medical document analysis against trusted medical sources
168+
*
169+
* @param analysis The medical document analysis to review
170+
* @param originalText The original text of the medical document
171+
* @returns The corrected medical document analysis
172+
*/
173+
async reviewMedicalAnalysis(analysis: any, originalText: string): Promise<any> {
174+
this.logger.log('Reviewing medical document analysis with Perplexity');
175+
176+
const systemPrompt =
177+
'You are an AI assistant specializing in medical information verification.\n' +
178+
'Your task is to review a medical document analysis and verify it against trusted medical sources.\n' +
179+
'You must ensure all information is accurate, especially lab value reference ranges and interpretations.\n' +
180+
'Use authoritative medical sources like Mayo Clinic, Cleveland Clinic, CDC, NIH, WHO, and medical journals.\n';
181+
182+
const analysisJson = JSON.stringify(analysis, null, 2);
183+
184+
const userPrompt =
185+
`Please review the following medical document analysis for accuracy and completeness. ` +
186+
`Check if the lab value reference ranges, interpretations, and recommendations align with trusted medical sources. ` +
187+
`Focus on these key aspects:\n` +
188+
`1. Verify lab value reference ranges\n` +
189+
`2. Confirm interpretations of abnormal values\n` +
190+
`3. Validate medical conclusions and recommendations\n` +
191+
`4. Ensure all lab values are correctly categorized\n\n` +
192+
`If you find any discrepancies, provide corrections in your response by returning the corrected JSON directly.\n\n` +
193+
`Medical Document Analysis:\n${analysisJson}\n\n` +
194+
`Original Medical Document Text:\n${originalText}\n\n` +
195+
`Return the corrected JSON analysis with the same structure, no preamble or explanation needed.`;
196+
197+
const messages: PerplexityMessage[] = [
198+
{ role: 'system', content: systemPrompt },
199+
{ role: 'user', content: userPrompt },
200+
];
201+
202+
try {
203+
const response = await this.queryPerplexityAI(messages, {
204+
temperature: 0.3, // Lower temperature for more accurate/factual responses
205+
maxTokens: 4000, // Ensure there's enough space for the full corrected analysis
206+
});
207+
208+
// Parse the response to get the corrected analysis
209+
const responseText = response.choices[0].message.content.trim();
210+
211+
try {
212+
// Try to parse as JSON - Perplexity should return the corrected JSON
213+
const correctedAnalysis = JSON.parse(responseText);
214+
return correctedAnalysis;
215+
} catch (jsonParseError) {
216+
// If parsing fails, log the error but return the original analysis
217+
this.logger.error(
218+
`Failed to parse Perplexity review response as JSON: ${jsonParseError instanceof Error ? jsonParseError.message : 'Unknown error'}`,
219+
);
220+
return analysis;
221+
}
222+
} catch (error) {
223+
// If the API call fails, log the error but return the original analysis
224+
this.logger.error(
225+
`Error during medical analysis review: ${error instanceof Error ? error.message : 'Unknown error'}`,
226+
);
227+
return analysis;
228+
}
229+
}
169230
}

0 commit comments

Comments
 (0)