feat(agent): 医院信息子代理改为本地文件知识库并接入双 bot
- 一院一 Markdown 档案(data/hospitals),索引与章节自动维护;读取支持 section 与 24k 截断,写入校验日期与单条长度,别名精确冲突时不新建 - 子代理按 allowWrite 分可写/只读工具集与提示词:管理端与陪诊员可写,就诊人端只读(物理移除写入工具) - 新增 scripts/import_hospitals.js 存量导入:压缩医生为一行、默认前 60 位,支持 dry-run、幂等与冲突报告,生成 112 家医院档案 - 管理端图片识别原文沿用原样回显策略,不再经模型二次整理 - npm test 212 项通过(新增知识库 12 项、导入 3 项)
This commit is contained in:
@@ -0,0 +1,489 @@
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import config from "../../../../config.js";
|
||||
|
||||
// 医院知识库默认章节:统一格式,允许按需新增
|
||||
export const DEFAULT_SECTIONS = [
|
||||
"基本信息",
|
||||
"联系电话",
|
||||
"医生与排班",
|
||||
"就诊流程",
|
||||
"检查检验",
|
||||
"住院手术",
|
||||
"交通停车",
|
||||
"陪诊注意",
|
||||
"其他",
|
||||
];
|
||||
|
||||
const SECTIONS_FILE = "_sections.md";
|
||||
const INDEX_FILE = "index.md";
|
||||
const FALLBACK_SECTION = "其他";
|
||||
|
||||
// 单次读取上限:超出时截断并提示按章节读取,避免整个档案塞进模型上下文
|
||||
export const MAX_READ_CHARS = 24000;
|
||||
// 单条写入上限:与「单文件 20-30 KB」的体积目标配套,防止长文灌入
|
||||
export const MAX_ENTRY_CHARS = 1000;
|
||||
|
||||
// 写操作串行执行:知识库写入频率低,用全局锁避免索引与医院文件互相覆盖
|
||||
let writeQueue = Promise.resolve();
|
||||
function withWriteLock(fn) {
|
||||
const run = writeQueue.then(fn, fn);
|
||||
writeQueue = run.then(() => undefined, () => undefined);
|
||||
return run;
|
||||
}
|
||||
|
||||
function formatDate(date = new Date()) {
|
||||
const y = date.getFullYear();
|
||||
const m = String(date.getMonth() + 1).padStart(2, "0");
|
||||
const d = String(date.getDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
function normalize(value) {
|
||||
return String(value ?? "").trim().toLowerCase().replace(/\s+/g, "");
|
||||
}
|
||||
|
||||
function normalizeSection(value) {
|
||||
return String(value ?? "").trim().replace(/[::]+$/, "");
|
||||
}
|
||||
|
||||
function escapeRegExp(value) {
|
||||
return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
// 精确定位章节标题,避免「基本信息」误匹配「基本信息补充」
|
||||
function findSection(text, section) {
|
||||
const regex = new RegExp(`^##\\s+${escapeRegExp(section)}\\s*$`, "m");
|
||||
const match = regex.exec(text);
|
||||
if (!match) return null;
|
||||
return { index: match.index, headingLength: match[0].length };
|
||||
}
|
||||
|
||||
// 档案里实际写有内容的章节
|
||||
function listContentSections(text) {
|
||||
return [...text.matchAll(/^##\s+(.+?)\s*$/gm)].map((match) => match[1].trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
// 截取单个章节(含标题行),用于按章节读取
|
||||
function sliceSection(text, section) {
|
||||
const range = findSection(text, section);
|
||||
if (!range) return null;
|
||||
const bodyStart = range.index + range.headingLength;
|
||||
const rest = text.slice(bodyStart);
|
||||
const next = /^##\s+/m.exec(rest);
|
||||
const end = next ? bodyStart + next.index : text.length;
|
||||
return text.slice(range.index, end).trim();
|
||||
}
|
||||
|
||||
export function isValidDate(value) {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
||||
const [year, month, day] = value.split("-").map(Number);
|
||||
const date = new Date(year, month - 1, day);
|
||||
return date.getFullYear() === year && date.getMonth() === month - 1 && date.getDate() === day;
|
||||
}
|
||||
|
||||
// 文件名只保留可读字符,避免 Windows 非法路径字符
|
||||
function toFileName(name) {
|
||||
const safe = String(name ?? "")
|
||||
.trim()
|
||||
.replace(/[\\/:*?"<>|]/g, "_")
|
||||
.replace(/[. ]+$/g, "")
|
||||
.slice(0, 80);
|
||||
return safe || "未命名医院";
|
||||
}
|
||||
|
||||
function parseSections(text) {
|
||||
return text
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.match(/^-\s+(.+)$/))
|
||||
.filter(Boolean)
|
||||
.map((match) => match[1].trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function serializeSections(sections) {
|
||||
return `# 医院信息章节\n\n${sections.map((item) => `- ${item}`).join("\n")}\n`;
|
||||
}
|
||||
|
||||
function parseIndex(text) {
|
||||
return text
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => line.startsWith("- "))
|
||||
.map((line) => {
|
||||
const fields = {};
|
||||
for (const part of line.slice(2).split(";")) {
|
||||
const index = part.indexOf(":");
|
||||
if (index <= 0) continue;
|
||||
fields[part.slice(0, index).trim()] = part.slice(index + 1).trim();
|
||||
}
|
||||
const name = fields["名称"];
|
||||
const file = fields["文件"];
|
||||
if (!name || !file) return null;
|
||||
return {
|
||||
name,
|
||||
aliases: (fields["别名"] || "").split("、").map((item) => item.trim()).filter(Boolean),
|
||||
city: fields["城市"] || "",
|
||||
file,
|
||||
};
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function serializeIndexEntry(entry) {
|
||||
const parts = [`名称:${entry.name}`];
|
||||
if (entry.aliases?.length) parts.push(`别名:${entry.aliases.join("、")}`);
|
||||
if (entry.city) parts.push(`城市:${entry.city}`);
|
||||
parts.push(`文件:${entry.file}`);
|
||||
return `- ${parts.join(";")}`;
|
||||
}
|
||||
|
||||
function serializeIndex(entries) {
|
||||
return `# 医院索引\n\n${entries.map(serializeIndexEntry).join("\n")}\n`;
|
||||
}
|
||||
|
||||
async function writeFileAtomic(file, content) {
|
||||
const temp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
||||
await fs.writeFile(temp, content, "utf8");
|
||||
await fs.rename(temp, file);
|
||||
}
|
||||
|
||||
async function readFileIfExists(file) {
|
||||
try {
|
||||
return await fs.readFile(file, "utf8");
|
||||
} catch (error) {
|
||||
if (error.code === "ENOENT") return null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 医院知识库:一院一文件,索引与章节清单单独维护。
|
||||
* 不依赖数据库,所有内容以 Markdown 文本保存。
|
||||
*/
|
||||
export function createHospitalKnowledgeStore({ rootDir, now = () => new Date() } = {}) {
|
||||
const root = rootDir || path.resolve(process.cwd(), config.agent?.dataDir ?? "data", "hospitals");
|
||||
const sectionsPath = path.join(root, SECTIONS_FILE);
|
||||
const indexPath = path.join(root, INDEX_FILE);
|
||||
let readyPromise = null;
|
||||
|
||||
async function ensureReady() {
|
||||
if (!readyPromise) {
|
||||
readyPromise = (async () => {
|
||||
await fs.mkdir(root, { recursive: true });
|
||||
if (!(await readFileIfExists(sectionsPath))) {
|
||||
await writeFileAtomic(sectionsPath, serializeSections(DEFAULT_SECTIONS));
|
||||
}
|
||||
if (!(await readFileIfExists(indexPath))) {
|
||||
await writeFileAtomic(indexPath, serializeIndex([]));
|
||||
}
|
||||
})();
|
||||
// 初始化失败时允许下次重试
|
||||
readyPromise.catch(() => {
|
||||
readyPromise = null;
|
||||
});
|
||||
}
|
||||
return readyPromise;
|
||||
}
|
||||
|
||||
async function getSections() {
|
||||
const text = (await readFileIfExists(sectionsPath)) || serializeSections(DEFAULT_SECTIONS);
|
||||
const sections = parseSections(text);
|
||||
return sections.length ? sections : [...DEFAULT_SECTIONS];
|
||||
}
|
||||
|
||||
async function getIndex() {
|
||||
const text = (await readFileIfExists(indexPath)) || serializeIndex([]);
|
||||
return parseIndex(text);
|
||||
}
|
||||
|
||||
async function addSection(section) {
|
||||
const sections = await getSections();
|
||||
if (sections.includes(section)) return sections;
|
||||
const next = [...sections];
|
||||
// 新章节统一插在「其他」之前,保证文件结构稳定
|
||||
const fallbackIndex = next.indexOf(FALLBACK_SECTION);
|
||||
if (fallbackIndex >= 0) next.splice(fallbackIndex, 0, section);
|
||||
else next.push(section);
|
||||
await writeFileAtomic(sectionsPath, serializeSections(next));
|
||||
return next;
|
||||
}
|
||||
|
||||
async function updateIndexEntry(entry) {
|
||||
const entries = await getIndex();
|
||||
const position = entries.findIndex((item) => item.file === entry.file);
|
||||
if (position >= 0) {
|
||||
const mergedAliases = [...new Set([...(entries[position].aliases || []), ...(entry.aliases || [])])];
|
||||
entries[position] = {
|
||||
...entries[position],
|
||||
name: entry.name || entries[position].name,
|
||||
aliases: mergedAliases,
|
||||
city: entry.city || entries[position].city,
|
||||
};
|
||||
} else {
|
||||
entries.push(entry);
|
||||
}
|
||||
await writeFileAtomic(indexPath, serializeIndex(entries));
|
||||
}
|
||||
|
||||
function findHospital(entries, query) {
|
||||
const target = normalize(query);
|
||||
if (!target) return { candidates: [] };
|
||||
const exact = entries.filter(
|
||||
(item) => normalize(item.name) === target || item.aliases.some((alias) => normalize(alias) === target),
|
||||
);
|
||||
if (exact.length === 1) return { entry: exact[0] };
|
||||
if (exact.length > 1) return { exactCandidates: exact, candidates: exact };
|
||||
|
||||
// 仅用于提示候选,不自动认定,避免把分院写到总院上
|
||||
const loose = entries.filter(
|
||||
(item) =>
|
||||
normalize(item.name).includes(target)
|
||||
|| target.includes(normalize(item.name))
|
||||
|| item.aliases.some((alias) => normalize(alias).includes(target) || target.includes(normalize(alias))),
|
||||
);
|
||||
return { candidates: loose };
|
||||
}
|
||||
|
||||
async function findAvailableFileName(name, entries) {
|
||||
const base = toFileName(name);
|
||||
const used = new Set(entries.map((item) => item.file));
|
||||
if (!used.has(`${base}.md`)) return `${base}.md`;
|
||||
for (let i = 2; i < 100; i += 1) {
|
||||
const candidate = `${base}-${i}.md`;
|
||||
if (!used.has(candidate)) return candidate;
|
||||
}
|
||||
return `${base}-${Date.now()}.md`;
|
||||
}
|
||||
|
||||
function buildHeader(name, aliases, city, date) {
|
||||
const lines = [`# ${name}`, ""];
|
||||
if (aliases.length) lines.push(`- 别名:${aliases.join("、")}`);
|
||||
if (city) lines.push(`- 城市:${city}`);
|
||||
lines.push(`- 最后更新:${date}`, "");
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function buildEntry({ content, url, source, date }) {
|
||||
return `- ${content}${url ? `:${url}` : ""}(来源:${source},${date})`;
|
||||
}
|
||||
|
||||
async function list() {
|
||||
await ensureReady();
|
||||
return {
|
||||
sections: await getSections(),
|
||||
index: parseIndex((await readFileIfExists(indexPath)) || ""),
|
||||
};
|
||||
}
|
||||
|
||||
async function read(hospital, { section } = {}) {
|
||||
await ensureReady();
|
||||
const entries = await getIndex();
|
||||
const { entry, candidates } = findHospital(entries, hospital);
|
||||
if (!entry) {
|
||||
return {
|
||||
found: false,
|
||||
candidates: candidates.map(({ name, aliases, city, file }) => ({ name, aliases, city, file })),
|
||||
};
|
||||
}
|
||||
const content = await readFileIfExists(path.join(root, entry.file));
|
||||
if (content === null) {
|
||||
return { found: false, candidates: [], error: `索引指向的文件不存在:${entry.file}` };
|
||||
}
|
||||
|
||||
const sections = listContentSections(content);
|
||||
let body = content;
|
||||
const sectionName = normalizeSection(section);
|
||||
if (sectionName) {
|
||||
const sliced = sliceSection(content, sectionName);
|
||||
if (!sliced) {
|
||||
return { found: true, ...entry, sectionMissing: true, sections, content: "" };
|
||||
}
|
||||
body = sliced;
|
||||
}
|
||||
|
||||
let truncated = false;
|
||||
let note = "";
|
||||
if (body.length > MAX_READ_CHARS) {
|
||||
body = body.slice(0, MAX_READ_CHARS);
|
||||
truncated = true;
|
||||
note = `内容超过 ${MAX_READ_CHARS} 字符已截断,请用 section 参数按章节读取。可用章节:${sections.join("、")}`;
|
||||
}
|
||||
|
||||
return { found: true, ...entry, content: body, sections, truncated, note };
|
||||
}
|
||||
|
||||
async function write({
|
||||
hospital,
|
||||
section,
|
||||
content,
|
||||
source = "未注明",
|
||||
date,
|
||||
url,
|
||||
mode = "append",
|
||||
match,
|
||||
aliases = [],
|
||||
city = "",
|
||||
createIfMissing = false,
|
||||
}) {
|
||||
return withWriteLock(async () => {
|
||||
await ensureReady();
|
||||
|
||||
const name = String(hospital ?? "").trim();
|
||||
const sectionName = normalizeSection(section);
|
||||
const text = String(content ?? "").trim().replace(/\r?\n+/g, " ");
|
||||
if (!name) throw new Error("医院名称不能为空");
|
||||
if (!sectionName) throw new Error("章节不能为空");
|
||||
if (!text) throw new Error("内容不能为空");
|
||||
if (text.length > MAX_ENTRY_CHARS) {
|
||||
throw new Error(`内容过长(${text.length} 字符),单条上限 ${MAX_ENTRY_CHARS} 字符,请拆分或精简`);
|
||||
}
|
||||
if (date && !isValidDate(date)) {
|
||||
throw new Error(`日期格式不正确:${date},请使用 YYYY-MM-DD`);
|
||||
}
|
||||
if (url) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
throw new Error(`链接格式不正确:${url}`);
|
||||
}
|
||||
if (!["http:", "https:"].includes(parsed.protocol)) {
|
||||
throw new Error("链接只支持 http/https");
|
||||
}
|
||||
}
|
||||
if (mode === "replace" && !String(match ?? "").trim()) {
|
||||
throw new Error("替换模式需要提供 match,用于定位原条目");
|
||||
}
|
||||
|
||||
const entryDate = date || formatDate(now());
|
||||
const cleanAliases = [...new Set(aliases.map((item) => String(item ?? "").trim()).filter(Boolean))];
|
||||
const entries = await getIndex();
|
||||
const { entry, exactCandidates, candidates } = findHospital(entries, name);
|
||||
|
||||
// 名称或别名精确命中多家时不能新建,否则会在冲突名下产生重复档案;
|
||||
// 这与 createIfMissing 无关——createIfMissing 只用于索引中确实不存在的医院
|
||||
if (!entry && exactCandidates?.length) {
|
||||
return {
|
||||
success: false,
|
||||
reason: "ambiguous",
|
||||
error: `「${name}」精确对应 ${exactCandidates.length} 家医院(名称或别名冲突),请使用索引中的正式名称。`,
|
||||
candidates: exactCandidates.map(({ name: candidateName, aliases: candidateAliases, city: candidateCity, file }) => ({
|
||||
name: candidateName,
|
||||
aliases: candidateAliases,
|
||||
city: candidateCity,
|
||||
file,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
if (!entry && !createIfMissing) {
|
||||
if (candidates.length) {
|
||||
return {
|
||||
success: false,
|
||||
reason: "ambiguous",
|
||||
error: `「${name}」可能对应多家医院,请确认后使用索引中的正式名称,或明确新建。`,
|
||||
candidates: candidates.map(({ name: candidateName, aliases: candidateAliases, city: candidateCity, file }) => ({
|
||||
name: candidateName,
|
||||
aliases: candidateAliases,
|
||||
city: candidateCity,
|
||||
file,
|
||||
})),
|
||||
};
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
reason: "not-found",
|
||||
error: `索引中没有「${name}」。确认是新医院时,传 createIfMissing=true 再写入。`,
|
||||
};
|
||||
}
|
||||
|
||||
let target = entry;
|
||||
let contentText = "";
|
||||
if (!target) {
|
||||
const fileName = await findAvailableFileName(name, entries);
|
||||
target = { name, aliases: cleanAliases, city, file: fileName };
|
||||
contentText = buildHeader(name, cleanAliases, city, entryDate);
|
||||
} else {
|
||||
contentText = (await readFileIfExists(path.join(root, target.file))) || buildHeader(target.name, target.aliases, target.city, entryDate);
|
||||
// 合并别名与城市,最终只写一次索引
|
||||
target = {
|
||||
...target,
|
||||
aliases: [...new Set([...(target.aliases || []), ...cleanAliases])],
|
||||
city: city || target.city,
|
||||
};
|
||||
}
|
||||
|
||||
const heading = `## ${sectionName}`;
|
||||
let sectionRange = findSection(contentText, sectionName);
|
||||
if (!sectionRange) {
|
||||
const other = findSection(contentText, FALLBACK_SECTION);
|
||||
const block = `${heading}\n`;
|
||||
if (other) {
|
||||
contentText = `${contentText.slice(0, other.index)}${block}\n${contentText.slice(other.index)}`;
|
||||
} else {
|
||||
contentText = `${contentText.replace(/\s+$/, "")}\n\n${block}`;
|
||||
}
|
||||
sectionRange = findSection(contentText, sectionName);
|
||||
}
|
||||
|
||||
const line = buildEntry({ content: text, url, source, date: entryDate });
|
||||
const bodyStart = sectionRange.index + sectionRange.headingLength;
|
||||
const nextHeading = /\n##\s+/g;
|
||||
nextHeading.lastIndex = bodyStart;
|
||||
const next = nextHeading.exec(contentText);
|
||||
const sectionEnd = next ? next.index : contentText.length;
|
||||
const before = contentText.slice(0, bodyStart);
|
||||
const body = contentText.slice(bodyStart, sectionEnd);
|
||||
const after = contentText.slice(sectionEnd);
|
||||
|
||||
let nextBody;
|
||||
if (mode === "replace") {
|
||||
const lines = body.split(/\r?\n/);
|
||||
const matched = lines
|
||||
.map((value, index) => ({ value, index }))
|
||||
.filter(({ value }) => value.startsWith("- ") && value.includes(String(match).trim()));
|
||||
if (matched.length === 0) {
|
||||
return { success: false, reason: "match-not-found", error: `未在「${sectionName}」中找到包含「${match}」的条目` };
|
||||
}
|
||||
if (matched.length > 1) {
|
||||
return {
|
||||
success: false,
|
||||
reason: "match-ambiguous",
|
||||
error: `「${match}」匹配到 ${matched.length} 条,请提供更精确的 match`,
|
||||
candidates: matched.map(({ value }) => value),
|
||||
};
|
||||
}
|
||||
lines[matched[0].index] = line;
|
||||
nextBody = lines.join("\n");
|
||||
} else {
|
||||
if (body.split(/\r?\n/).some((value) => value.trim() === line)) {
|
||||
return { success: true, duplicate: true, hospital: target.name, section: sectionName, file: target.file, line };
|
||||
}
|
||||
nextBody = `${body.replace(/\s+$/, "")}\n${line}\n`;
|
||||
}
|
||||
|
||||
contentText = `${before}${nextBody}${after}`;
|
||||
// 刷新头部更新时间
|
||||
contentText = /- 最后更新:.*/.test(contentText)
|
||||
? contentText.replace(/- 最后更新:.*/, `- 最后更新:${entryDate}`)
|
||||
: contentText.replace(/^(# .+\n)/, `$1\n- 最后更新:${entryDate}\n`);
|
||||
|
||||
// 校验通过后再登记新章节,避免失败写入留下空章节
|
||||
await addSection(sectionName);
|
||||
await writeFileAtomic(path.join(root, target.file), contentText);
|
||||
await updateIndexEntry(target);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
hospital: target.name,
|
||||
section: sectionName,
|
||||
file: target.file,
|
||||
line,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
return { root, list, read, write, ensureReady };
|
||||
}
|
||||
|
||||
export const hospitalKnowledgeStore = createHospitalKnowledgeStore();
|
||||
Reference in New Issue
Block a user