import { DBModel } from "../../../models/index.js"; import logger from "../../../utils/logger.js"; import { normalizeInquiry } from "../../../utils/inquiry.js"; import { MEDIA_LIMITS, MediaInputError, decodeBase64Media, normalizeAudioMeta, normalizeImageMeta, recognizeAudio, recognizeImage, } from "../../infra/media/index.js"; import { medicalInquiryAgent } from "./agent.js"; import { extractPdfText, MAX_PDF_BYTES } from "./pdf.js"; export const INQUIRY_JOB_LIMITS = Object.freeze({ maxMaterials: 6, maxTotalBytes: 12 * 1024 * 1024, maxTextChars: 10000, // 单轮全部材料转写文字总和:给模型输入留足上下文余量,超出提示分批。 maxSourceChars: 30000, ttlMs: 24 * 60 * 60 * 1000, }); function requiredText(value, label, maxLength) { const text = String(value ?? "").trim(); if (text.length > maxLength) throw new MediaInputError(`${label}过长(最多 ${maxLength} 字)`); return text; } export function normalizeJobInputs(body = {}) { const text = requiredText(body.text, "补充文字", INQUIRY_JOB_LIMITS.maxTextChars); if (body.materials !== undefined && !Array.isArray(body.materials)) { throw new MediaInputError("材料列表格式不正确"); } const materials = body.materials || []; if (materials.length > INQUIRY_JOB_LIMITS.maxMaterials) { throw new MediaInputError(`每次最多上传 ${INQUIRY_JOB_LIMITS.maxMaterials} 份材料`); } if (!text && materials.length === 0) { throw new MediaInputError("请添加 PDF、图片、语音或补充文字"); } let totalBytes = 0; const normalized = materials.map((material, index) => { const type = String(material?.type || ""); const label = `第 ${index + 1} 份材料`; let bytes; let meta; if (type === "image") { meta = normalizeImageMeta(material); bytes = decodeBase64Media(material.data, { maxBytes: MEDIA_LIMITS.maxImageBytes, label: "图片" }); } else if (type === "audio") { meta = normalizeAudioMeta(material); bytes = decodeBase64Media(material.data, { maxBytes: MEDIA_LIMITS.maxAudioBytes, label: "音频" }); } else if (type === "pdf") { meta = { mime: "application/pdf" }; bytes = decodeBase64Media(material.data, { maxBytes: MAX_PDF_BYTES, label: "PDF" }); } else { throw new MediaInputError(`${label}类型不支持`); } totalBytes += bytes.length; if (totalBytes > INQUIRY_JOB_LIMITS.maxTotalBytes) { throw new MediaInputError("本次材料总大小不能超过 12MB,请分批整理"); } return { type, name: String(material.name || label).trim().slice(0, 120) || label, data: bytes.toString("base64"), ...meta, }; }); return { text, materials: normalized, current: normalizeInquiry(body.current) }; } export function toInquiryJobView(job) { return { id: String(job._id), recordId: String(job.recordId), status: job.status, draft: normalizeInquiry(job.draft), uncertainties: Array.isArray(job.uncertainties) ? job.uncertainties : [], errorMessage: job.errorMessage || "", createdAt: job.createdAt, updatedAt: job.updatedAt, }; } function safeProcessError(err) { if (err instanceof MediaInputError || err?.status === 400) return err.message; if (/not configured|api key missing/i.test(err?.message || "")) return "病历解析服务暂不可用"; if (/没有可整理/.test(err?.message || "")) return err.message; return "病历整理失败,请稍后重试"; } export class MedicalInquiryTask { constructor(options = {}) { this.agent = options.agent || medicalInquiryAgent; } async create({ record, userId, body }) { const inputs = normalizeJobInputs(body); const active = await DBModel.InquiryParseJob.findOne({ recordId: record._id, userId, active: true, }).lean(); // 同一订单重复提交时返回活动任务,客户端刷新或重进页面可直接续接。 if (active) return active; let job; try { job = await DBModel.InquiryParseJob.create({ recordId: record._id, userId, inputs, baseUpdatedAt: record.meta?.updatetime || null, expiresAt: new Date(Date.now() + INQUIRY_JOB_LIMITS.ttlMs), }); } catch (err) { if (err?.code !== 11000) throw err; job = await DBModel.InquiryParseJob.findOne({ recordId: record._id, userId, active: true }).lean(); if (!job) throw err; return job; } setImmediate(() => { this.process(job._id).catch((err) => { logger.error("medical inquiry job terminated unexpectedly", { jobId: String(job._id), error: err?.name || "Error" }); }); }); return job; } async process(jobId) { const job = await DBModel.InquiryParseJob.findOneAndUpdate( { _id: jobId, status: "queued" }, { $set: { status: "processing", errorMessage: "" } }, { new: true } ).select("+inputs"); if (!job) return; try { const materials = []; if (job.inputs?.text) { materials.push({ type: "text", name: "用户补充文字", text: job.inputs.text }); } for (const material of job.inputs?.materials || []) { const bytes = Buffer.from(material.data, "base64"); // 识别函数只接元信息,不把整段 base64 再带进调用栈。 const meta = { mime: material.mime, width: material.width, height: material.height, kind: material.kind, codec: material.codec, rate: material.rate, channels: material.channels, format: material.format, }; let text = ""; if (material.type === "pdf") text = await extractPdfText(bytes); else if (material.type === "image") text = await recognizeImage(bytes, meta); else if (material.type === "audio") text = await recognizeAudio(bytes, meta); if (!String(text || "").trim()) throw new MediaInputError(`${material.name}未识别到有效内容`); materials.push({ type: material.type, name: material.name, text: String(text).trim() }); } const sourceChars = materials.reduce((sum, item) => sum + item.text.length, 0); if (sourceChars > INQUIRY_JOB_LIMITS.maxSourceChars) { throw new MediaInputError("材料文字过多,请分批整理(每次最多约 3 万字)"); } const result = await this.agent.parse({ materials, current: job.inputs?.current || {} }); await DBModel.InquiryParseJob.updateOne( { _id: jobId, status: "processing" }, { $set: { status: "waiting_confirmation", draft: normalizeInquiry(result), uncertainties: result.uncertainties || [], }, $unset: { inputs: 1 }, } ); } catch (err) { logger.warn("medical inquiry job failed", { jobId: String(jobId), error: err?.name || "Error", }); await DBModel.InquiryParseJob.updateOne( { _id: jobId, status: "processing" }, { $set: { status: "failed", active: false, errorMessage: safeProcessError(err) }, $unset: { inputs: 1 } } ); } finally { // 取消等分支也必须清除原件;日志只记录任务 ID 和错误类型,不记录医疗正文。 await DBModel.InquiryParseJob.updateOne({ _id: jobId }, { $unset: { inputs: 1 } }); } } } export const medicalInquiryTask = new MedicalInquiryTask(); export default medicalInquiryTask;