Skip to content

Commit 526410c

Browse files
authored
Merge pull request #135 from ModusCreateOrg/ADE-208
[ADE-208] Update critical instructions in PerplexityService to clarify metadata handling
2 parents 268d152 + d272580 commit 526410c

File tree

4 files changed

+41
-46
lines changed

4 files changed

+41
-46
lines changed

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

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,24 @@ import {
88
import { RateLimiter } from '../../utils/security.utils';
99
import { createHash } from 'crypto';
1010

11+
export interface LabValue {
12+
name: string;
13+
value: string;
14+
unit: string;
15+
normalRange: string;
16+
status: 'normal' | 'high' | 'low';
17+
isCritical: boolean;
18+
conclusion: string;
19+
suggestions: string;
20+
}
21+
1122
/**
1223
* Interface for medical document analysis result
1324
*/
1425
export interface MedicalDocumentAnalysis {
1526
title: string;
1627
category: string;
17-
labValues: Array<{
18-
name: string;
19-
value: string;
20-
unit: string;
21-
normalRange: string;
22-
status: 'normal' | 'high' | 'low';
23-
isCritical: boolean;
24-
conclusion: string;
25-
suggestions: string;
26-
}>;
28+
labValues: LabValue[];
2729
medicalComments: string;
2830
metadata: {
2931
isMedicalReport: boolean;

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,12 @@ describe('DocumentProcessorService', () => {
4848
// Create a new test-specific instance with proper mocking
4949
const testTextractService = { extractText: vi.fn() };
5050
const testBedrockService = { analyzeMedicalDocument: vi.fn() };
51-
const testPerplexityService = { reviewMedicalAnalysis: vi.fn() };
51+
const testPerplexityService = { reviewLabValuesAnalysis: vi.fn() };
5252

5353
// Set up mocks
5454
testTextractService.extractText.mockResolvedValue(extractedTextResult);
5555
testBedrockService.analyzeMedicalDocument.mockResolvedValue(medicalAnalysis);
56-
testPerplexityService.reviewMedicalAnalysis.mockResolvedValue(medicalAnalysis);
56+
testPerplexityService.reviewLabValuesAnalysis.mockResolvedValue(medicalAnalysis);
5757

5858
// Create a fresh service instance with our mocks
5959
const testService = new DocumentProcessorService(
@@ -71,7 +71,7 @@ describe('DocumentProcessorService', () => {
7171
extractedTextResult.rawText,
7272
userId,
7373
);
74-
expect(testPerplexityService.reviewMedicalAnalysis).toHaveBeenCalled();
74+
expect(testPerplexityService.reviewLabValuesAnalysis).toHaveBeenCalled();
7575
expect(result).toEqual({
7676
extractedText: extractedTextResult,
7777
analysis: medicalAnalysis,
@@ -89,7 +89,7 @@ describe('DocumentProcessorService', () => {
8989
// Create test-specific service with proper mocking
9090
const testTextractService = { extractText: vi.fn() };
9191
const testBedrockService = { analyzeMedicalDocument: vi.fn() };
92-
const testPerplexityService = { reviewMedicalAnalysis: vi.fn() };
92+
const testPerplexityService = { reviewLabValuesAnalysis: vi.fn() };
9393

9494
// Make the mock reject with an error
9595
testTextractService.extractText.mockRejectedValue(new Error('Failed to extract text'));
@@ -120,7 +120,7 @@ describe('DocumentProcessorService', () => {
120120
// Create test-specific service with proper mocking
121121
const testTextractService = { extractText: vi.fn() };
122122
const testBedrockService = { analyzeMedicalDocument: vi.fn() };
123-
const testPerplexityService = { reviewMedicalAnalysis: vi.fn() };
123+
const testPerplexityService = { reviewLabValuesAnalysis: vi.fn() };
124124

125125
// Create a fresh service instance with our mocks
126126
const testService = new DocumentProcessorService(

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

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,29 +54,26 @@ export class DocumentProcessorService {
5454
});
5555

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

6262
// Step 3: Review and verify analysis using Perplexity
6363
this.logger.log('Reviewing medical analysis with Perplexity');
6464

65-
let analysis: MedicalDocumentAnalysis;
66-
6765
try {
68-
const verifiedAnalysis = await this.perplexityService.reviewMedicalAnalysis(
69-
initialAnalysis,
66+
const verifiedLabValues = await this.perplexityService.reviewLabValuesAnalysis(
67+
analysis.labValues,
7068
extractedText.rawText,
7169
);
72-
analysis = verifiedAnalysis;
70+
analysis.labValues = verifiedLabValues;
71+
7372
this.logger.log('Analysis verified and possibly corrected by Perplexity');
7473
} catch (reviewError) {
7574
this.logger.error('Error reviewing analysis with Perplexity', {
7675
error: reviewError instanceof Error ? reviewError.message : 'Unknown error',
7776
});
78-
// Fall back to initial analysis if review fails
79-
analysis = initialAnalysis;
8077
}
8178

8279
const processingTime = Date.now() - startTime;

backend/src/services/perplexity.service.ts

Lines changed: 19 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { Injectable, Logger } from '@nestjs/common';
22
import { ConfigService } from '@nestjs/config';
33
import axios from 'axios';
44
import { AwsSecretsService } from './aws-secrets.service';
5-
import { MedicalDocumentAnalysis } from 'src/document-processor/services/aws-bedrock.service';
5+
import { LabValue } from 'src/document-processor/services/aws-bedrock.service';
66

77
export interface PerplexityMessage {
88
role: 'system' | 'user' | 'assistant';
@@ -247,31 +247,27 @@ export class PerplexityService {
247247
}
248248

249249
/**
250-
* Reviews and verifies a medical document analysis against trusted medical sources
250+
* Reviews and verifies a medical document lab values against trusted medical sources
251251
*
252-
* @param analysis The medical document analysis to review
252+
* @param labValues The medical document lab values to review
253253
* @param originalText The original text of the medical document
254-
* @returns The corrected medical document analysis
254+
* @returns The corrected medical document lab values
255255
*/
256-
async reviewMedicalAnalysis(
257-
analysis: MedicalDocumentAnalysis,
258-
originalText: string,
259-
): Promise<any> {
260-
this.logger.log('Reviewing medical document analysis with Perplexity');
256+
async reviewLabValuesAnalysis(labValues: LabValue[], originalText: string): Promise<LabValue[]> {
257+
this.logger.log('Reviewing medical document lab values with Perplexity');
261258

262259
const systemPrompt =
263-
'Medical information verification specialist. Verify analysis against trusted sources (Mayo Clinic, Cleveland Clinic, CDC, NIH, WHO, medical journals). Ensure accuracy of lab ranges, interpretations, and recommendations. Return only corrected JSON. IMPORTANT: Do not modify the metadata object.';
260+
'Medical information verification specialist. Verify lab values against trusted sources (Mayo Clinic, Cleveland Clinic, CDC, NIH, WHO, medical journals). Ensure accuracy of lab ranges, interpretations, and recommendations. Return only corrected JSON. IMPORTANT: Do not modify the metadata object.';
264261

265-
const analysisJson = JSON.stringify(analysis, null, 2);
262+
const labValuesJson = JSON.stringify(labValues, null, 2);
266263

267264
const userPrompt =
268-
`Review this medical analysis for accuracy. Verify:\n` +
265+
`Review this medical lab values for accuracy. Verify:\n` +
269266
`1. Lab value reference ranges\n` +
270267
`2. Interpretations of abnormal values\n` +
271268
`3. Medical conclusions and recommendations\n` +
272269
`4. Lab value categorizations\n\n` +
273-
`CRITICAL INSTRUCTION: Do NOT modify the metadata object.\n\n` +
274-
`Analysis JSON:\n${analysisJson}\n\n` +
270+
`Analysis JSON:\n${labValuesJson}\n\n` +
275271
`Original Text:\n${originalText}\n\n` +
276272
`Return ONLY corrected JSON with identical structure. No preamble, explanation, or text before/after JSON.`;
277273

@@ -283,30 +279,30 @@ export class PerplexityService {
283279
try {
284280
const response = await this.createChatCompletion(messages, {
285281
temperature: 0.3, // Lower temperature for more accurate/factual responses
286-
maxTokens: 4000, // Ensure there's enough space for the full corrected analysis
282+
maxTokens: 4000, // Ensure there's enough space for the full corrected labValues
287283
responseFormat: { type: 'json_object' }, // Use JSON mode for reliable JSON response
288284
});
289285

290-
// Parse the response to get the corrected analysis
286+
// Parse the response to get the corrected labValues
291287
const responseText = response.choices[0].message.content.trim();
292288

293289
try {
294290
// Try to parse as JSON - Perplexity should return the corrected JSON
295-
const correctedAnalysis = JSON.parse(responseText);
296-
return correctedAnalysis;
291+
const correctedLabValues = JSON.parse(responseText);
292+
return correctedLabValues;
297293
} catch (jsonParseError) {
298-
// If parsing fails, log the error but return the original analysis
294+
// If parsing fails, log the error but return the original labValues
299295
this.logger.error(
300296
`Failed to parse Perplexity review response as JSON: ${jsonParseError instanceof Error ? jsonParseError.message : 'Unknown error'}`,
301297
);
302-
return analysis;
298+
return labValues;
303299
}
304300
} catch (error) {
305-
// If the API call fails, log the error but return the original analysis
301+
// If the API call fails, log the error but return the original labValues
306302
this.logger.error(
307-
`Error during medical analysis review: ${error instanceof Error ? error.message : 'Unknown error'}`,
303+
`Error during medical labValues review: ${error instanceof Error ? error.message : 'Unknown error'}`,
308304
);
309-
return analysis;
305+
return labValues;
310306
}
311307
}
312308
}

0 commit comments

Comments
 (0)