调整了agent

This commit is contained in:
lik
2026-10-28 11:15:29 +08:00
parent b8f53d3660
commit c4f6be6494
29 changed files with 703 additions and 921 deletions
+62 -49
View File
@@ -3,43 +3,72 @@ import z from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
function createEscortRecordQueryTool(userInfo) {
const userId = userInfo?._id;
const STATUS_VALUES = ["pending", "confirmed", "in_progress", "completed", "cancelled"];
const STATUS_DESC =
"Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)";
/**
* 陪诊记录查询工具
*
* 用户端与管理端共用同一套查询实现,差异只有两处:
* - 用户端强制按 userId 隔离,且不暴露手机号筛选;
* - 管理端可跨用户查询,并支持按患者手机号精确筛选。
* 两端不会出现在同一个 Agent 中,因此可以共用工具名 escort_record_query。
*/
function buildEscortRecordQueryTool({ userId = null, allowMobile = false } = {}) {
const shape = {
patientName: z.string().optional().describe("Patient name for fuzzy search"),
status: z.enum(STATUS_VALUES).optional().describe(STATUS_DESC),
page: z.number().int().min(1).optional().describe("Page number, starting from 1"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("Records per page (1-50), default 20"),
};
if (allowMobile) {
shape.mobile = z.string().optional().describe("Patient mobile phone number for exact match");
}
return tool(
async ({ patientName, status, page = 1, pageSize = 20 }) => {
async ({ patientName, mobile, status, page = 1, pageSize = 20 }) => {
try {
const filter = {};
if (!userId && !allowMobile) {
return { success: false, error: "用户未登录,无法查询陪诊记录" };
}
const filter = { deletedAt: null };
if (patientName) {
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
}
// 按订单归属用户过滤:不能用手机号作为隔离键,
// 因为手机号可由用户自行修改(改到他人号码即可读到他人订单)
if (!userId) {
return {
success: false,
error: "用户未登录,无法查询陪诊记录",
};
if (allowMobile && mobile) {
filter["patient.mobile"] = mobile;
}
filter.userId = userId;
// 软删除的订单对用户端不可见
filter.deletedAt = null;
if (status) {
filter.status = status;
}
// 用户端按订单归属过滤;不能用手机号作为隔离键(手机号可由用户自行修改)
if (userId) {
filter.userId = userId;
}
const skip = (page - 1) * pageSize;
const records = await DBModel.EscortRecord.find(filter)
.sort({ "schedule.date": -1 })
.skip(skip)
.limit(pageSize)
.lean();
const total = await DBModel.EscortRecord.countDocuments(filter);
const [records, total] = await Promise.all([
DBModel.EscortRecord.find(filter)
.sort({ "schedule.date": -1 })
.skip(skip)
.limit(pageSize)
.lean(),
DBModel.EscortRecord.countDocuments(filter),
]);
return {
success: true,
@@ -57,35 +86,19 @@ function createEscortRecordQueryTool(userInfo) {
},
{
name: "escort_record_query",
description:
"Query escort records from database for the current user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current logged-in user.",
schema: z.object({
patientName: z
.string()
.optional()
.describe("Patient name for fuzzy search"),
status: z
.enum(["pending", "confirmed", "in_progress", "completed", "cancelled"])
.optional()
.describe(
"Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)"
),
page: z
.number()
.int()
.min(1)
.optional()
.describe("Page number, starting from 1"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("Records per page (1-50), default 20"),
}),
description: allowMobile
? "Query all escort records (admin scope). Supports filtering by patient name, mobile phone number, and appointment status. Returns paginated results sorted by appointment date in descending order."
: "Query escort records of the current logged-in user. Supports filtering by patient name and appointment status. Returns paginated results sorted by appointment date in descending order. The query is automatically scoped to the current user.",
schema: z.object(shape),
}
);
}
export { createEscortRecordQueryTool };
/** 用户端:按当前登录用户隔离 */
const createEscortRecordQueryTool = (userInfo) =>
buildEscortRecordQueryTool({ userId: userInfo?._id });
/** 管理端:跨用户查询,支持手机号 */
const escortRecordQueryTool = buildEscortRecordQueryTool({ allowMobile: true });
export { createEscortRecordQueryTool, escortRecordQueryTool };
@@ -1,80 +0,0 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
const escortRecordQueryTool = tool(
async ({ patientName, mobile, status, page = 1, pageSize = 20 }) => {
try {
const filter = { deletedAt: null };
if (patientName) {
filter["patient.name"] = { $regex: escapeRegex(patientName), $options: "i" };
}
if (mobile) {
filter["patient.mobile"] = mobile;
}
if (status) {
filter.status = status;
}
const skip = (page - 1) * pageSize;
const records = await DBModel.EscortRecord.find(filter)
.sort({ "schedule.date": -1 })
.skip(skip)
.limit(pageSize)
.lean();
const total = await DBModel.EscortRecord.countDocuments(filter);
return {
success: true,
data: records,
};
} catch (error) {
return {
success: false,
error: error.message,
};
}
},
{
name: "escort_record_query",
description:
"Query escort records from database. Supports filtering by patient name, mobile phone number, and appointment status. Returns paginated results sorted by appointment date in descending order.",
schema: z.object({
patientName: z
.string()
.optional()
.describe("Patient name for fuzzy search"),
mobile: z
.string()
.optional()
.describe("Patient mobile phone number for exact match"),
status: z
.enum(["pending", "confirmed", "in_progress", "completed", "cancelled"])
.optional()
.describe(
"Appointment status: pending (待确认), confirmed (已确认), in_progress (进行中), completed (已完成), cancelled (已取消)"
),
page: z
.number()
.int()
.min(1)
.optional()
.describe("Page number, starting from 1"),
pageSize: z
.number()
.int()
.min(1)
.max(50)
.optional()
.describe("Records per page (1-50), default 20"),
}),
}
);
export { escortRecordQueryTool };
+2 -2
View File
@@ -2,6 +2,7 @@ import { tool } from "@langchain/core/tools";
import z from "zod";
import mongoose from "mongoose";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
const healthProfileQueryTool = tool(
async ({ profileId, userId, name, mobile, page = 1, pageSize = 20 }) => {
@@ -28,8 +29,7 @@ const healthProfileQueryTool = tool(
}
if (name) {
// 转义正则特殊字符,避免查询报错或 ReDoS;姓名支持中文、全拼、拼音首字母匹配
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = { $regex: escaped, $options: "i" };
const re = { $regex: escapeRegex(name), $options: "i" };
filter.$or = [{ "profile.name": re }, { "profile.pinyin": re }, { "profile.pinyinFL": re }];
}
if (mobile) {
-32
View File
@@ -1,32 +0,0 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { DBModel } from "../../../../models/index.js";
const hospitalInfoGetTool = tool(
async ({ hospitalId }) => {
try {
if (!hospitalId) {
return { success: false, error: "hospitalId 不能为空" };
}
const org = await DBModel.Organization.findById(hospitalId).lean();
if (!org) {
return { success: false, error: `未找到 id 为「${hospitalId}」的机构` };
}
return { success: true, data: org };
} catch (error) {
return { success: false, error: error.message };
}
},
{
name: "hospital_info_get",
description:
"根据医院 id 获取医院完整信息。id 可通过 hospital_info_list 获取。",
schema: z.object({
hospitalId: z.string().describe("医院 id(MongoDB ObjectId,来自 hospital_info_list)"),
}),
}
);
export { hospitalInfoGetTool };
+6 -8
View File
@@ -1,24 +1,22 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
const hospitalInfoListTool = tool(
async ({ keyword }) => {
try {
const filter = {};
if (keyword) {
const escaped = String(keyword).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const re = { $regex: escaped, $options: "i" };
const re = { $regex: escapeRegex(keyword), $options: "i" };
filter.$or = [{ name: re }, { pinyin: re }, { pinyinFL: re }];
}
const total = await DBModel.Organization.countDocuments(filter);
// 轻量列表:只取 id+名称,用于先定位医院,再按 id 查详情
const orgs = await DBModel.Organization.find(filter)
.sort({ name: 1 })
.limit(1000)
.select("name")
.lean();
const [total, orgs] = await Promise.all([
DBModel.Organization.countDocuments(filter),
DBModel.Organization.find(filter).sort({ name: 1 }).limit(1000).select("name").lean(),
]);
return { success: true, total, data: orgs.map((o) => ({ id: o._id, name: o.name })) };
} catch (error) {
+35 -10
View File
@@ -1,23 +1,44 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import mongoose from "mongoose";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
/**
* 医院信息查询工具
*
* 两种用法:
* - 传 hospitalId:返回该院完整档案(id 可先用 hospital_info_list 获取);
* - 传 hospitalName:按名称模糊查询,并可按科室 / 医生名过滤,返回面向上层展示的精简字段。
*/
const hospitalInfoQueryTool = tool(
async ({ hospitalName, department, doctorName }) => {
async ({ hospitalId, hospitalName, department, doctorName }) => {
try {
if (!hospitalName) {
return { success: false, error: "hospitalName 不能为空" };
if (hospitalId) {
if (!mongoose.Types.ObjectId.isValid(hospitalId)) {
return { success: false, error: `Invalid hospital ID: ${hospitalId}` };
}
const org = await DBModel.Organization.findById(hospitalId).lean();
if (!org) {
return { success: false, error: `未找到 id 为「${hospitalId}」的机构` };
}
return { success: true, total: 1, data: [org] };
}
const filter = { name: { $regex: hospitalName, $options: "i" } };
const total = await DBModel.Organization.countDocuments(filter);
if (!hospitalName) {
return { success: false, error: "请提供 hospitalId 或 hospitalName" };
}
const filter = { name: { $regex: escapeRegex(hospitalName), $options: "i" } };
// 医院总量小,一次最多取 10 家,命中过多时由调用方细化名称
const [total, orgs] = await Promise.all([
DBModel.Organization.countDocuments(filter),
DBModel.Organization.find(filter).limit(10).lean(),
]);
if (total === 0) {
return { success: false, error: `未找到名称包含「${hospitalName}」的机构` };
}
// 医院总量小,一次最多取 10 家,命中过多时由调用方细化名称
const orgs = await DBModel.Organization.find(filter).limit(10).lean();
const data = orgs.map((org) => {
const fa = org.forAgent ?? {};
let departments = fa.departments ?? [];
@@ -51,9 +72,13 @@ const hospitalInfoQueryTool = tool(
{
name: "hospital_info_query",
description:
"查询医院就医信息:医院总览(门诊/挂号/缴费/医保/交通)、科室(位置/电话/就诊提示)、医生(职称/擅长/号别/坐班)、场景指南(初诊/住院/检查须知/老人服务)、照片。按医院名称模糊查询,可按科室、医生名过滤。最多返回 10 家医院信息。",
"查询医院就医信息。传 hospitalId 返回该院完整档案;传 hospitalName 按名称模糊查询,可再按科室、医生名过滤,返回医院总览(门诊/挂号/缴费/医保/交通)、科室(位置/电话/就诊提示)、医生(职称/擅长/号别/坐班)、场景指南、照片。最多返回 10 家医院。",
schema: z.object({
hospitalName: z.string().describe("医院名称,支持模糊匹配(如 协和)"),
hospitalId: z
.string()
.optional()
.describe("医院 id(MongoDB ObjectId,来自 hospital_info_list),提供时忽略其他查询条件"),
hospitalName: z.string().optional().describe("医院名称,支持模糊匹配(如 协和)"),
department: z.string().optional().describe("科室名称过滤(如 风湿免疫科、放射科)"),
doctorName: z.string().optional().describe("医生姓名过滤"),
}),
+5 -2
View File
@@ -1,6 +1,7 @@
import { tool } from "@langchain/core/tools";
import z from "zod";
import { DBModel } from "../../../../models/index.js";
import { escapeRegex } from "./utils.js";
const hospitalInfoSetTool = tool(
async ({ hospitalName, section, action, content, guides, entry, entryName, updatedBy }) => {
@@ -9,8 +10,10 @@ const hospitalInfoSetTool = tool(
return { success: false, error: "hospitalName 不能为空" };
}
// 定位医院:名称必须唯一命中
const orgs = await DBModel.Organization.find({ name: { $regex: hospitalName, $options: "i" } }).exec();
// 定位医院:名称必须唯一命中;转义正则元字符,避免非法表达式与 ReDoS
const orgs = await DBModel.Organization.find({
name: { $regex: escapeRegex(hospitalName), $options: "i" },
}).exec();
if (orgs.length === 0) {
return { success: false, error: `未找到名称包含「${hospitalName}」的机构,请确认医院名称后重试` };
}