Fix ai-service Dockerfile: bake in drug_entities.json, override its path

This commit is contained in:
2026-08-10 10:35:13 +07:00
parent a4b8e1c4db
commit 60b4397032
51 changed files with 4302 additions and 2087 deletions
+28 -2
View File
@@ -1,9 +1,26 @@
export interface Citation {
chunkId: string;
drugName: string;
sectionType: string;
/** Printed page numbers as they appear in the book — what a clinician reads off their paper copy. */
sourcePageRange: [number, number];
snippet?: string;
reason?: string;
/** PyMuPDF 0-indexed page of the physical PDF file — NOT the printed page. Add 1 for a `#page=` viewer fragment. */
physicalPage: number;
/** The exact chunk text retrieved and handed to the LLM/grounding check — not a paraphrase. */
snippet: string;
/** True when this chunk carries a table/formula the pipeline quarantined (never linearised into text). */
isQuarantined: boolean;
/** Present only when `isQuarantined` — a truthful notice, not boilerplate. */
quarantineNotice?: string;
/**
* The quarantined table/formula's OWN physical page, when it differs from
* `physicalPage` (a table often sits on the page after the paragraph that
* mentions it — verified on real data, not assumed). Falls back to
* `physicalPage` when absent. Only meaningful when `isQuarantined`.
*/
quarantinePhysicalPage?: number;
/** A rendered crop of the source table/formula, when reconstruction has produced one. Usually absent today. */
sourceCropUrl?: string;
}
export interface ChatMessage {
@@ -16,8 +33,17 @@ export interface ChatMessage {
decision?: string;
reason?: string;
grounded?: boolean;
/** True: the LLM paraphrased the evidence and it passed grounding+entailment. False: verbatim source quote (no generator configured, or a configured one that failed and abstained). */
generated?: boolean;
resolvedDrugId?: string;
createdAt: string;
/**
* Short suggested replies for a `decision: "clarify"` turn — e.g. ["Người
* lớn", "Trẻ em"] for an age-band question. Optional: the model doesn't
* always produce clean short options (an open-ended clarify has none),
* and the UI must fall back to free text either way.
*/
quickReplies?: string[];
}
export interface SendMessageRequest {
+146 -71
View File
@@ -14,14 +14,25 @@ import {
RotateCcw,
ExternalLink,
BookOpen,
CornerDownRight,
} from "lucide-react";
import { cn } from "./lib/utils";
interface ChatBubbleProps {
message: ChatMessage;
onCitationClick?: (citation: Citation, index: number) => void;
// `allCitations` is THIS message's own citation list (`message.citations`)
// — found live 2026-08-07: the caller previously had no way to know which
// message a click came from, so it kept showing whatever citation array a
// LATER message had most recently loaded. Clicking [1] on an old answer
// (e.g. Omeprazol's mechanism) displayed a completely unrelated later
// drug's evidence (e.g. Kanamycin) in the source panel — a real, live-
// reported bug for a product whose entire value proposition is a
// verifiable citation trail.
onCitationClick?: (citation: Citation, index: number, allCitations: Citation[]) => void;
activeCitationIndex?: number | null;
onRetry?: () => void;
/** Fired when the user picks a quick-reply chip instead of typing — sends that text as the next turn. */
onQuickReply?: (text: string) => void;
className?: string;
}
@@ -30,6 +41,7 @@ export function ChatBubble({
onCitationClick,
activeCitationIndex,
onRetry,
onQuickReply,
className,
}: ChatBubbleProps) {
const [copied, setCopied] = useState(false);
@@ -51,83 +63,92 @@ export function ChatBubble({
);
}
// Citation markers must render INLINE within whatever block (paragraph/
// bullet/heading) they end the sentence of — never split out as a bare
// top-level element. Found live 2026-08-07: the old approach split the
// WHOLE content on `[n]` first and only then broke each piece into lines,
// so a citation sitting on its own source line (a common shape for a
// multi-band dosing answer, e.g. "...5,4 g/ngày\n[1]\n; cấp tính...") ended
// up as a bare `<button>` between two block-level `<p>`s — visually its
// own orphaned line, fragmenting a short list into a choppy one-clause-
// per-line mess instead of a readable paragraph or bullet list.
const renderInline = (text: string, keyPrefix: string, citations?: Citation[]) => {
const segments = text.split(/(\[\d+\])/g);
return segments.map((seg, i) => {
const match = seg.match(/^\[(\d+)\]$/);
if (!match) {
return <React.Fragment key={`${keyPrefix}-t-${i}`}>{formatBoldText(seg)}</React.Fragment>;
}
const citationIndex = parseInt(match[1], 10);
const citationObj = citations && citations[citationIndex - 1];
const isActive = activeCitationIndex === citationIndex;
return (
<button
key={`${keyPrefix}-c-${i}`}
id={`citation-marker-${citationIndex}`}
onClick={() => {
if (citationObj) {
onCitationClick?.(citationObj, citationIndex, citations ?? []);
}
}}
title={citationObj ? `${citationObj.drugName} (${citationObj.sectionType})` : `Trích dẫn [${citationIndex}]`}
className={cn(
"inline-flex items-center justify-center min-w-[1.25rem] h-5 px-1.5 mx-0.5 rounded-full text-[0.68rem] font-extrabold tracking-tight transition-all align-baseline cursor-pointer select-none",
isActive
? "bg-accent-primary text-txt-inverse scale-110 shadow-md ring-2 ring-accent-glow glass-beam-glow"
: "bg-accent-soft text-accent-primary hover:bg-accent-primary hover:text-txt-inverse border border-border-subtle"
)}
>
{citationIndex}
</button>
);
});
};
// Helper to parse citations [1], [2] in markdown content
const renderStructuredContent = (content: string, citations?: Citation[]) => {
// Split content by citations like [1], [2], etc.
const parts = content.split(/(\[\d+\])/g);
return parts.map((part, i) => {
const match = part.match(/^\[(\d+)\]$/);
if (match) {
const citationIndex = parseInt(match[1], 10);
const citationObj = citations && citations[citationIndex - 1];
const isActive = activeCitationIndex === citationIndex;
const lines = content.split("\n");
return lines.map((line, lineIdx) => {
if (!line.trim()) return <br key={lineIdx} />;
// Heading 2 or 3
if (line.startsWith("### ") || line.startsWith("## ")) {
return (
<button
key={`cite-${i}`}
id={`citation-marker-${citationIndex}`}
onClick={() => {
if (citationObj) {
onCitationClick?.(citationObj, citationIndex);
}
}}
title={citationObj ? `${citationObj.drugName} (${citationObj.sectionType})` : `Trích dẫn [${citationIndex}]`}
className={cn(
"inline-flex items-center justify-center min-w-[1.25rem] h-5 px-1.5 mx-0.5 rounded-full text-[0.68rem] font-extrabold tracking-tight transition-all align-baseline cursor-pointer select-none",
isActive
? "bg-accent-primary text-txt-inverse scale-110 shadow-md ring-2 ring-accent-glow glass-beam-glow"
: "bg-accent-soft text-accent-primary hover:bg-accent-primary hover:text-txt-inverse border border-border-subtle"
)}
>
[{citationIndex}]
</button>
<h3 key={lineIdx} className="text-base font-extrabold text-txt-primary mt-3 mb-1.5 flex items-center gap-2">
<span className="w-1.5 h-4 rounded-full bg-accent-primary inline-block" />
{renderInline(line.replace(/^#+\s*/, ""), `h-${lineIdx}`, citations)}
</h3>
);
}
// Format markdown-like text lines
const lines = part.split("\n");
// Bullet points
if (line.trim().startsWith("- ") || line.trim().startsWith("* ")) {
return (
<li key={lineIdx} className="ml-4 list-disc text-txt-secondary mb-1">
{renderInline(line.trim().replace(/^[-*]\s*/, ""), `li-${lineIdx}`, citations)}
</li>
);
}
// Warning block / Note
if (line.includes("Chống chỉ định") || line.includes("Cảnh báo") || line.includes("Thận trọng")) {
return (
<div key={lineIdx} className="my-2 rounded-xl border border-status-warning/40 bg-status-warning-bg/60 p-3 text-xs leading-relaxed text-txt-primary flex items-start gap-2.5">
<AlertTriangle className="h-4 w-4 text-status-warning shrink-0 mt-0.5" />
<div>{renderInline(line, `w-${lineIdx}`, citations)}</div>
</div>
);
}
// The primary clinical answer text — the one thing on this whole card
// a clinician actually needs to read, so it carries more visual
// weight than the surrounding header/footer chrome (found live
// 2026-08-07: previously the same low-emphasis size/weight as
// everything else, easy to skim past).
return (
<React.Fragment key={`text-${i}`}>
{lines.map((line, lineIdx) => {
if (!line.trim()) return <br key={lineIdx} />;
// Heading 2 or 3
if (line.startsWith("### ") || line.startsWith("## ")) {
return (
<h3 key={lineIdx} className="text-base font-extrabold text-txt-primary mt-3 mb-1.5 flex items-center gap-2">
<span className="w-1.5 h-4 rounded-full bg-accent-primary inline-block" />
{line.replace(/^#+\s*/, "")}
</h3>
);
}
// Bullet points
if (line.trim().startsWith("- ") || line.trim().startsWith("* ")) {
return (
<li key={lineIdx} className="ml-4 list-disc text-txt-secondary mb-1">
{formatBoldText(line.trim().replace(/^[-*]\s*/, ""))}
</li>
);
}
// Warning block / Note
if (line.includes("Chống chỉ định") || line.includes("Cảnh báo") || line.includes("Thận trọng")) {
return (
<div key={lineIdx} className="my-2 rounded-xl border border-status-warning/40 bg-status-warning-bg/60 p-3 text-xs leading-relaxed text-txt-primary flex items-start gap-2.5">
<AlertTriangle className="h-4 w-4 text-status-warning shrink-0 mt-0.5" />
<div>{formatBoldText(line)}</div>
</div>
);
}
return (
<p key={lineIdx} className="mb-2 text-txt-primary text-sm leading-relaxed">
{formatBoldText(line)}
</p>
);
})}
</React.Fragment>
<p key={lineIdx} className="mb-2 text-txt-primary text-[0.95rem] font-medium leading-relaxed">
{renderInline(line, `p-${lineIdx}`, citations)}
</p>
);
});
};
@@ -175,11 +196,21 @@ export function ChatBubble({
</div>
<div className="flex items-center gap-2">
{message.grounded !== false ? (
{message.decision === "answerable" && message.grounded !== false ? (
<span className="inline-flex items-center gap-1 rounded-full border border-status-success/30 bg-status-success-bg px-2.5 py-0.5 text-[0.65rem] font-extrabold text-status-success">
<ShieldCheck className="h-3 w-3" />
ENTAILED & GROUNDED
</span>
) : message.decision === "verify_pdf" ? (
<span className="inline-flex items-center gap-1 rounded-full border border-status-warning/30 bg-status-warning-bg px-2.5 py-0.5 text-[0.65rem] font-extrabold text-status-warning">
<AlertTriangle className="h-3 w-3" />
CẦN ĐI CHIẾU PDF GỐC
</span>
) : message.decision === "clarify" ? (
<span className="inline-flex items-center gap-1 rounded-full border border-border-accent/40 bg-accent-soft px-2.5 py-0.5 text-[0.65rem] font-extrabold text-accent-primary">
<Info className="h-3 w-3" />
CẦN LÀM CÂU HỎI
</span>
) : (
<span className="inline-flex items-center gap-1 rounded-full border border-status-warning/30 bg-status-warning-bg px-2.5 py-0.5 text-[0.65rem] font-extrabold text-status-warning">
<Info className="h-3 w-3" />
@@ -187,6 +218,33 @@ export function ChatBubble({
</span>
)}
{/* How the answer was produced from the retrieved evidence — only
meaningful for a real answerable turn (rag/answer.py's two
operating modes: LLM paraphrase vs. verbatim quote). A clarify
or verify_pdf turn is neither, so it gets no source-mode pill. */}
{message.decision === "answerable" && message.grounded !== false && message.generated !== undefined && (
<span
title={
message.generated
? "Câu trả lời do LLM diễn giải lại từ chuyên luận gốc, đã qua kiểm tra grounding + entailment."
: "Trích dẫn nguyên văn từ chuyên luận gốc, không qua diễn giải của LLM."
}
className="inline-flex items-center gap-1 rounded-full border border-border-subtle bg-surface-elevated px-2.5 py-0.5 text-[0.65rem] font-bold text-txt-secondary"
>
{message.generated ? (
<>
<Sparkles className="h-3 w-3 text-accent-primary" />
AI diễn giải, đã kiểm chứng
</>
) : (
<>
<BookOpen className="h-3 w-3 text-accent-primary" />
Trích dẫn nguyên văn
</>
)}
</span>
)}
<time className="text-[0.68rem] text-txt-muted hidden sm:inline">
{new Date(message.createdAt).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
</time>
@@ -198,6 +256,23 @@ export function ChatBubble({
{renderStructuredContent(message.content, message.citations)}
</div>
{/* Quick-reply chips — only for a clarify turn the model gave a few
natural discrete answers to; free text always still works. */}
{message.quickReplies && message.quickReplies.length > 0 && (
<div className="px-4 pb-3 flex flex-wrap gap-2">
{message.quickReplies.map((reply, idx) => (
<button
key={idx}
onClick={() => onQuickReply?.(reply)}
className="inline-flex items-center gap-1.5 rounded-full border border-border-accent bg-accent-soft px-3 py-1.5 text-xs font-bold text-accent-primary hover:bg-accent-primary hover:text-txt-inverse transition-colors"
>
<CornerDownRight className="h-3 w-3" />
{reply}
</button>
))}
</div>
)}
{/* Disclaimer Section inside document */}
{message.disclaimer && (
<div className="mx-4 mb-3 rounded-xl border border-border-subtle bg-surface-elevated/50 p-2.5 text-[0.72rem] text-txt-muted flex items-start gap-2">
+54 -17
View File
@@ -2,7 +2,7 @@
import React from "react";
import type { Citation } from "@duoc-thu/shared-types";
import { BookOpen, FileText, CheckCircle2, ChevronRight } from "lucide-react";
import { BookOpen, FileText, ChevronRight, AlertTriangle, ExternalLink } from "lucide-react";
import { cn } from "./lib/utils";
interface CitationCardProps {
@@ -13,16 +13,31 @@ interface CitationCardProps {
className?: string;
}
// Matches the real 19-field section_key enum the corpus is chunked on
// (apps/ai-service/rag/understanding.py SECTION_KEY_HINTS) — the previous
// map here used guessed keys (lieu_dung, tac_dung_phu, duoc_ly, qua_lieu,
// bao_quan) that never matched a real chunk, so every citation silently
// fell back to the raw slug instead of a readable label.
const SECTION_LABELS: Record<string, string> = {
ten_chung_quoc_te: "Tên chung quốc tế",
ten_thuong_mai: "Tên thương mại",
ma_atc: "Mã ATC",
loai_thuoc: "Phân loại thuốc",
dang_thuoc_va_ham_luong: "Dạng thuốc & Hàm lượng",
duoc_ly_va_co_che_tac_dung: "Dược lý & Cơ chế tác dụng",
chi_dinh: "Chỉ định",
chong_chi_dinh: "Chống chỉ định",
lieu_dung: "Liều lượng & Cách dùng",
tac_dung_phu: "Tác dụng không mong muốn (ADR)",
than_trong: "Thận trọng",
thoi_ky_mang_thai: "Thời kỳ mang thai",
thoi_ky_cho_con_bu: "Thời kỳ cho con bú",
tac_dung_khong_mong_muon: "Tác dụng không mong muốn (ADR)",
huong_dan_xu_tri_adr: "Hướng dẫn xử trí ADR",
lieu_luong_va_cach_dung: "Liều lượng & Cách dùng",
tuong_tac_thuoc: "Tương tác thuốc",
duoc_ly: "Dược lý & Cơ chế tác dụng",
than_trong: "Thận trọng khi dùng",
qua_lieu: "Quá liều & Xử trí",
bao_quan: "Bảo quản",
qua_lieu_va_xu_tri: "Quá liều & Xử trí",
do_on_dinh_va_bao_quan: "Độ ổn định & Bảo quản",
tuong_ky: "Tương kỵ",
thong_tin_quy_che: "Thông tin quy chế",
};
export function CitationCard({
@@ -95,21 +110,43 @@ export function CitationCard({
</span>
</div>
{/* Snippet / Source Excerpt */}
{/* Snippet / Source Excerpt - the exact retrieved chunk text, verbatim */}
{citation.snippet && (
<div className="relative rounded-xl border border-border-subtle bg-surface-elevated/70 p-2.5 text-[0.75rem] leading-relaxed text-txt-secondary italic font-sans">
<span className="not-italic text-accent-primary font-bold mr-1"></span>
<div className="relative rounded-xl border border-border-subtle bg-surface-elevated/70 p-2.5 text-[0.75rem] leading-relaxed text-txt-secondary italic font-sans max-h-40 overflow-y-auto">
<span className="not-italic text-accent-primary font-bold mr-1">&ldquo;</span>
{citation.snippet}
<span className="not-italic text-accent-primary font-bold ml-1"></span>
<span className="not-italic text-accent-primary font-bold ml-1">&rdquo;</span>
</div>
)}
{/* Reason / Entailment Note */}
{citation.reason && (
<p className="m-0 text-[0.68rem] leading-snug text-txt-muted flex items-start gap-1">
<CheckCircle2 className="h-3 w-3 text-status-success shrink-0 mt-0.5" />
<span>{citation.reason}</span>
</p>
{/* Quarantine notice - only rendered when the source pipeline actually
flagged this chunk (table/formula lifted out of prose), never a
generic boilerplate line for an ordinary citation. */}
{citation.isQuarantined && (
<div className="rounded-xl border border-status-warning/40 bg-status-warning-bg/50 p-2.5 text-[0.7rem] leading-snug text-txt-primary space-y-1.5">
<p className="m-0 flex items-start gap-1.5">
<AlertTriangle className="h-3.5 w-3.5 text-status-warning shrink-0 mt-0.5" />
<span>{citation.quarantineNotice}</span>
</p>
{citation.sourceCropUrl ? (
<img
src={citation.sourceCropUrl}
alt={`Ảnh chụp bảng/công thức trang in ${citation.sourcePageRange[0]}`}
className="w-full rounded-lg border border-border-subtle"
/>
) : (
<a
href={`/api/pdf#page=${(citation.quarantinePhysicalPage ?? citation.physicalPage) + 1}`}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className="inline-flex items-center gap-1 rounded-lg bg-surface px-2 py-1 font-semibold text-accent-primary hover:underline"
>
<ExternalLink className="h-3 w-3" />
Mở trang PDF gốc đ đi chiếu
</a>
)}
</div>
)}
<div className="flex items-center justify-end text-[0.65rem] font-medium text-accent-primary group-hover:translate-x-0.5 transition-transform">