diff --git a/src/i18n/en/submissions.json b/src/i18n/en/submissions.json index a061dab..9388e6d 100644 --- a/src/i18n/en/submissions.json +++ b/src/i18n/en/submissions.json @@ -15,6 +15,9 @@ "emptyChoiceId": "Choice Id should be provided as answer.", "emptyChoiceIds": "Choice Ids should be provided as answer.", "transitionNotFound": "No transition found for the test", - "uniqueSubmissionQuestion": "Question's Answer already exists." + "uniqueSubmissionQuestion": "Question's Answer already exists.", + "submissionNotCompleted": "This submission is not completed yet.", + "noAnswers": "No answers found to analyze.", + "analysisFailed": "The analysis failed. Please try again." } } diff --git a/src/i18n/fa/submissions.json b/src/i18n/fa/submissions.json index 5779e2a..cbd7918 100644 --- a/src/i18n/fa/submissions.json +++ b/src/i18n/fa/submissions.json @@ -15,6 +15,9 @@ "emptyChoiceId": "شناسه گزینه باید به عنوان پاسخ مشخص شود.", "emptyChoiceIds": "لیستی از شناسه گزینه ها باید به عنوان پاسخ مشخص شود.", "transitionNotFound": "مسیری برای تست پیدا نشد.", - "uniqueSubmissionQuestion": "این سوال قبلا پاسخ داده شده است." + "uniqueSubmissionQuestion": "این سوال قبلا پاسخ داده شده است.", + "submissionNotCompleted": "این Submission هنوز تکمیل نشده است.", + "noAnswers": "هیچ پاسخی برای تحلیل یافت نشد.", + "analysisFailed": "تحلیل با خطا مواجه شد. لطفا دوباره تلاش کنید." } } diff --git a/src/modules/submissions/constants/analysis.constants.ts b/src/modules/submissions/constants/analysis.constants.ts new file mode 100644 index 0000000..866400c --- /dev/null +++ b/src/modules/submissions/constants/analysis.constants.ts @@ -0,0 +1,56 @@ +export const SUBMISSION_ANALYSIS_SYSTEM_PROMPT = ` + You are a medical risk analysis assistant for Heala (Or in persian: هیلا), + a health questionnaire platform. + + You will receive a completed health questionnaire: the test title, its + description, and the user's answer to every question in it. + + Your task is to analyze all of the questions and answers and assess the + probability that the user is currently suffering from a health condition + or disease related to this questionnaire. + + Analysis guidelines: + - Base your analysis strictly on the provided questions and answers. + Never invent symptoms, findings or information that is not present in them. + - Look for patterns, combinations and severity signals across the answers + (e.g. multiple high-risk answers reinforcing each other), not just + isolated values. + - Estimate the overall probability that the user's answers indicate an + existing medical condition as a percentage, and classify the overall + risk level as one of: کم, متوسط, بالا. + - Explicitly highlight answers that act as red flags. If the answers + suggest a medical emergency, clearly instruct the user to seek + immediate medical care. + - You are not a doctor and this is not a diagnosis. This is a + probabilistic screening based on a questionnaire. Communicate + uncertainty honestly and always recommend consulting a qualified + physician for a real diagnosis. + - Do not prescribe medications or dosages. + - Do not fabricate medical information. + + Write the entire analysis in Persian (فارسی) using exactly the following + markdown structure: + + ## خلاصه تحلیل + Two or three sentences summarizing the overall assessment. + + ## سطح ریسک + State the risk level (کم / متوسط / بالا) and the estimated probability + (احتمال تقریبی: xx٪) with a one-sentence justification. + + ## تحلیل پاسخ‌ها + Bullet points going through the notable answers and explaining what + each one implies. + + ## علائم هشدار + List the red flags found in the answers, or state that none were found. + + ## توصیه‌ها + Concrete and practical next steps: lifestyle advice, self-care, + follow-up actions, and which medical specialist to consult if relevant. + + ## سلب مسئولیت + A short paragraph clarifying that this analysis is probabilistic and + educational, not a medical diagnosis, and that a qualified physician + must be consulted. +`; diff --git a/src/modules/submissions/http/submissions.post.endpoints.http b/src/modules/submissions/http/submissions.post.endpoints.http index 259a095..4e75f13 100644 --- a/src/modules/submissions/http/submissions.post.endpoints.http +++ b/src/modules/submissions/http/submissions.post.endpoints.http @@ -15,3 +15,6 @@ Authorization: Bearer {{$global.accessToken}} // "numericValue": 1 // "choiceIds": [] } + +POST {{baseUrl}}/submissions/1/analyze +Authorization: Bearer {{$global.accessToken}} diff --git a/src/modules/submissions/providers/analyze/analyze-submission.provider.ts b/src/modules/submissions/providers/analyze/analyze-submission.provider.ts new file mode 100644 index 0000000..e8ec53d --- /dev/null +++ b/src/modules/submissions/providers/analyze/analyze-submission.provider.ts @@ -0,0 +1,209 @@ +import { HttpStatus, Injectable } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; +import { InjectRepository } from '@nestjs/typeorm'; +import { Repository } from 'typeorm'; +import { Submission } from '../../entities/submission.entity'; +import { SubmissionAnswer } from '../../entities/submission-answer.entity'; +import { SubmissionStatus } from '../../enums/submission-status.enum'; +import { AppException } from '@/common/exceptions/app.exception'; +import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception'; +import { User } from '@/modules/users/entities/user.entity'; +import { SUBMISSION_ANALYSIS_SYSTEM_PROMPT } from '../../constants/analysis.constants'; + +@Injectable() +export class AnalyzeSubmissionProvider { + constructor( + /** + * Inject Submission Repository + */ + @InjectRepository(Submission) + private readonly submissionRepository: Repository, + + /** + * Inject Submission Answer Repository + */ + @InjectRepository(SubmissionAnswer) + private readonly submissionAnswerRepository: Repository, + + /** + * Inject Config Service + */ + private readonly configService: ConfigService, + ) {} + + /** + * Validates and prepares the submission analysis, then returns an async + * generator streaming the analysis content chunk by chunk. + * + * Throws before streaming starts, so HTTP errors reach the client as + * regular error responses. + */ + public async analyze( + id: string, + user: User, + ): Promise> { + const submissionId = Number(id); + + if (Number.isNaN(submissionId)) { + throw new AppException( + 'validation.wrongFieldFormat', + HttpStatus.BAD_REQUEST, + { field: '$t(submissions.fields.submissionId)' }, + ); + } + + let submission: Submission | null = null; + + try { + submission = await this.submissionRepository.findOne({ + where: { + id: submissionId, + user: { + id: user.id, + }, + }, + relations: { + test: true, + }, + }); + } catch (err) { + throw new AppTimeoutException(err); + } + + if (!submission) { + throw new AppException( + 'common.errors.entityNotFound', + HttpStatus.NOT_FOUND, + { + entity: '$t(submissions.fields.submission)', + }, + ); + } + + if (submission.status !== SubmissionStatus.COMPLETED) { + throw new AppException( + 'submissions.errors.submissionNotCompleted', + HttpStatus.BAD_REQUEST, + ); + } + + let answers: SubmissionAnswer[] = []; + + try { + answers = await this.submissionAnswerRepository.find({ + where: { + submission: { + id: submission.id, + }, + }, + relations: { + question: true, + choice: true, + choices: true, + }, + order: { + id: 'ASC', + }, + }); + } catch (err) { + throw new AppTimeoutException(err); + } + + if (answers.length === 0) { + throw new AppException( + 'submissions.errors.noAnswers', + HttpStatus.BAD_REQUEST, + ); + } + + return this.streamAnalysis( + this.buildQuestionnaireMessage(submission, answers), + ); + } + + private buildQuestionnaireMessage( + submission: Submission, + answers: Array, + ): string { + const questionsAndAnswers = answers + .map( + (answer, index) => + `${index + 1}. ${answer.question.content}\nپاسخ: ${this.formatAnswer(answer)}`, + ) + .join('\n\n'); + + return [ + `عنوان آزمون: ${submission.test.title}`, + `توضیحات آزمون: ${submission.test.description}`, + '', + 'سوالات و پاسخ‌های کاربر:', + '', + questionsAndAnswers, + ].join('\n'); + } + + private formatAnswer(answer: SubmissionAnswer): string { + if (answer.choice) { + return answer.choice.text; + } + + if (answer.choices && answer.choices.length > 0) { + return answer.choices.map((choice) => choice.text).join('، '); + } + + if (answer.numericValue !== null && answer.numericValue !== undefined) { + return answer.numericValue.toString(); + } + + if (answer.textValue) { + return answer.textValue; + } + + return 'بی‌پاسخ'; + } + + private async getOpenRouter() { + const { OpenRouter } = await import('@openrouter/sdk'); + + return new OpenRouter({ + apiKey: this.configService.getOrThrow('openRouter.apiKey'), + }); + } + + private async *streamAnalysis( + questionnaire: string, + ): AsyncGenerator { + const openRouter = await this.getOpenRouter(); + + const response = await openRouter.chat.send({ + chatRequest: { + model: this.configService.getOrThrow('openRouter.model'), + messages: [ + { + role: 'system' as const, + content: SUBMISSION_ANALYSIS_SYSTEM_PROMPT.trim(), + }, + { + role: 'user' as const, + content: questionnaire, + }, + ], + stream: true, + }, + }); + + if ('choices' in response) { + throw new Error('Expected streaming response'); + } + + for await (const chunk of response) { + const content = chunk.choices[0]?.delta?.content; + + if (!content) { + continue; + } + + yield content; + } + } +} diff --git a/src/modules/submissions/providers/submissions.service.ts b/src/modules/submissions/providers/submissions.service.ts index ade3131..5155719 100644 --- a/src/modules/submissions/providers/submissions.service.ts +++ b/src/modules/submissions/providers/submissions.service.ts @@ -5,6 +5,7 @@ import { AnswerSubmissionProvider } from './answer/answer-submission.provider'; import { AnswerSubmissionDTO } from '../dtos/answer-submission.dto'; import { SubmissionHistoryProvider } from './history/submission-history.provider'; import { UserSubmissionListingProvider } from './listing/user-submission-listing.provider'; +import { AnalyzeSubmissionProvider } from './analyze/analyze-submission.provider'; @Injectable() export class SubmissionsService { @@ -28,6 +29,11 @@ export class SubmissionsService { * Inject User Submission Listing Provider */ private readonly userSubmissionListingProvider: UserSubmissionListingProvider, + + /** + * Inject Analyze Submission Provider + */ + private readonly analyzeSubmissionProvider: AnalyzeSubmissionProvider, ) {} public async startSubmission(testId: number, user?: User) { @@ -53,4 +59,11 @@ export class SubmissionsService { public async getUserSubmissions(user: User) { return await this.userSubmissionListingProvider.getSubmissionsList(user); } + + public async analyzeSubmission( + id: string, + user: User, + ): Promise> { + return await this.analyzeSubmissionProvider.analyze(id, user); + } } diff --git a/src/modules/submissions/submissions.controller.ts b/src/modules/submissions/submissions.controller.ts index cb37c91..8f22427 100644 --- a/src/modules/submissions/submissions.controller.ts +++ b/src/modules/submissions/submissions.controller.ts @@ -6,8 +6,10 @@ import { HttpStatus, Param, Post, + Res, UseGuards, } from '@nestjs/common'; +import { ApiResponse } from '@nestjs/swagger'; import { Public } from '../auth/decorators/public.decorator'; import { OptionalJwtGuard } from '../auth/guards/optional-jwt.guard'; import { User } from '../users/entities/user.entity'; @@ -21,6 +23,7 @@ import { StartGuestDTO } from './dtos/responses/start-guest.dto'; import { GetAnswerSubmissionDTO } from './dtos/responses/get-answer-submission.dto'; import { GetSubmissionHistoryDTO } from './dtos/responses/get-submission-history.dto'; import { GetSubmissionDetailDTO } from './dtos/responses/get-submission-detail.dto'; +import type { Response } from 'express'; @Controller('submissions') export class SubmissionsController { @@ -160,4 +163,85 @@ export class SubmissionsController { public async getUserSubmissions(@ActiveUser() user: User) { return await this.submissionsService.getUserSubmissions(user); } + + @Post(':id/analyze') + @HttpCode(HttpStatus.OK) + @ApiResponse({ + status: HttpStatus.OK, + description: + 'تحلیل سلامت به صورت Server-Sent Events استریم می‌شود. هر event شامل یک قطعه از تحلیل است و در پایان event نهایی با done: true ارسال می‌شود.', + content: { + 'text/event-stream': { + schema: { + type: 'string', + example: + 'data: {"content":"## خلاصه تحلیل\\n\\n..."}\n\ndata: {"content":"..."}\n\ndata: {"done":true}\n\n', + }, + }, + }, + }) + @ApiAppResponse([ + { + status: HttpStatus.UNAUTHORIZED, + variants: [ + { + messageExample: 'ابتدا وارد حساب کاربری خود شوید.', + }, + ], + }, + { + status: HttpStatus.BAD_REQUEST, + variants: [ + { + messageExample: 'شناسه Submission معتبر نیست.', + }, + { + messageExample: 'این Submission هنوز تکمیل نشده است.', + }, + { + messageExample: 'هیچ پاسخی برای تحلیل یافت نشد.', + }, + ], + }, + { + status: HttpStatus.NOT_FOUND, + variants: [ + { + messageExample: 'Submission مورد نظر یافت نشد.', + }, + ], + }, + ]) + public async analyzeSubmission( + @Param('id') id: string, + @ActiveUser() user: User, + @Res() res: Response, + ) { + /** + * Validation and preparation happen before streaming starts, so any + * error here reaches the client as a regular HTTP error response. + */ + const analysis = await this.submissionsService.analyzeSubmission(id, user); + + res.setHeader('Content-Type', 'text/event-stream'); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Connection', 'keep-alive'); + res.flushHeaders(); + + try { + for await (const content of analysis) { + res.write(`data: ${JSON.stringify({ content })}\n\n`); + } + + res.write(`data: ${JSON.stringify({ done: true })}\n\n`); + } catch { + res.write( + `data: ${JSON.stringify({ + error: 'submissions.errors.analysisFailed', + })}\n\n`, + ); + } finally { + res.end(); + } + } } diff --git a/src/modules/submissions/submissions.module.ts b/src/modules/submissions/submissions.module.ts index 2dd0e32..8bbc86e 100644 --- a/src/modules/submissions/submissions.module.ts +++ b/src/modules/submissions/submissions.module.ts @@ -18,6 +18,7 @@ import { HistoryAuthenticatedProvider } from './providers/history/history-authen import { HistoryGuestProvider } from './providers/history/history-guest.provider'; import { SubmissionHistoryProvider } from './providers/history/submission-history.provider'; import { UserSubmissionListingProvider } from './providers/listing/user-submission-listing.provider'; +import { AnalyzeSubmissionProvider } from './providers/analyze/analyze-submission.provider'; @Module({ imports: [ @@ -38,6 +39,7 @@ import { UserSubmissionListingProvider } from './providers/listing/user-submissi HistoryGuestProvider, SubmissionHistoryProvider, UserSubmissionListingProvider, + AnalyzeSubmissionProvider, SubmissionsService, ], })